logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
top
Sep 27, 2011 Posted on Sep 27, 2011 in Hints and Tips | 10 comments

Quick Tip: Use SWFObject to Embed Your Flash Content

In this Quick Tip screencast, I’ll show you how to embed your Flash SWFs in an HTML webpage using SWFObject.


Where to Get SWFObject

The latest version of SWFObject is available on its Google Code page. Grab whichever file is marked as “Featured” on this page (at time of writing, that’s version 2.2).


Watch the Screencast

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


The Starting HTML

For a beginner’s guide to HTML, see this tutorial.

<!DOCTYPE html>
<html>
	<head>
		<title></title>
	</head>
	<body></body>
</html>

The Final HTML

<!DOCTYPE html>
<html>
	<head>
		<title>Our HTML Page</title>
		<script type="text/javascript" src="swfobject.js"></script>
		<script type="text/javascript">swfobject.embedSWF('animation.swf', 'flash', '550', '400', '9.0.0');</script>
	</head>
	<body>
		<div id="flash">
			<p>At this moment you do not support Flash Player 9. We're sorry.</p>
		</div>
	</body>
</html>

Thank You

Thank you for watching, if you have any questions, feel free to comment.



View full post on Activetuts+

banner ad

10 Responses to “Quick Tip: Use SWFObject to Embed Your Flash Content”

  1. Daniel Apt says:
    September 27, 2011 at 3:16 am

    In this Quick Tip screencast, I’ll show you how to embed your Flash SWFs in an HTML webpage using SWFObject.


    Where to Get SWFObject

    The latest version of SWFObject is available on its Google Code page. Grab whichever file is marked as “Featured” on this page (at time of writing, that’s version 2.2).


    Watch the Screencast

    Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


    The Starting HTML

    For a beginner’s guide to HTML, see this tutorial.

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title></title>
    	</head>
    	<body></body>
    </html>
    

    The Final HTML

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>Our HTML Page</title>
    		<script type="text/javascript" src="swfobject.js"></script>
    		<script type="text/javascript">swfobject.embedSWF('animation.swf', 'flash', '550', '400', '9.0.0');</script>
    	</head>
    	<body>
    		<div id="flash">
    			<p>At this moment you do not support Flash Player 9. We're sorry.</p>
    		</div>
    	</body>
    </html>
    

    Thank You

    Thank you for watching, if you have any questions, feel free to comment.


  2. James Tyner says:
    September 27, 2011 at 3:47 am

    In this tutorial I will introduce a class by Senocular.com that allows easy movement of game characters with minimal code.


    Final Result Preview

    In the SWF you’ll see a spaceship; use your Left, Right, Up, and Down arrow keys to move it.


    Step 1: Explanation of KeyObject.as

    When ActionScript 3.0 came out we lost the functionality of AS2′s Key.isDown() method. Senocular has coded a great little class that will let us emulate this functionality within actionscript 3 and that is what we will look at in the tutorial.


    Step 2: Setting Up the Project

    Go to File > New and create a new Actionscript 3.0 document, with the following properties:

    • Size: 550 * 400
    • Background Color: White
    • FPS: 24

    Save this file as "KeyObject.fla"


    Step 3: Downloading KeyObject.as

    Before we can code our application we need to get the "KeyObject.as" file, so head over to Senocular.com. Under the Flash Menu, click on Actionscript. Once there you will want to drill down to "KeyObject.as" and download it. Get there by going to Actionscript 3.0 > com > senocular > utils.

    KeyObject Flash tutorial for AS3

    You can right-click on the download link and save it as "KeyObject.as".

    Once you have done this you need to remove com.senocular.utils right after the package declaration in the file, since we are not using the com.senocular class path.

    Change this:

    
    
    package com.senocular.utils {
        import flash.display.Stage;
        import flash.events.KeyboardEvent;
    	//Rest of Class
    

    To this:

    
    
    package {
        import flash.display.Stage;
        import flash.events.KeyboardEvent;
    	//Rest of Class
    

    Step 4: Importing the Player Graphic

    In the download files there is a spaceship image called player.png. In Flash, import this to the stage, by going to File > Import > Import To Stage. Right-click on it and choose "Convert To Symbol", give it the symbol name "player", and make sure the registration point is set to the top left. Now give it the instance name of "player" as well.

    KeyObject Flash tutorial for AS3
    KeyObject Flash tutorial for AS3

    Step 5: Setting Up the Main Class

    Go to File > New and choose ActionScript File.

    KeyObject Flash tutorial for AS3

    Save this as Main.as and set it as your Document Class within "KeyObject.fla".

    Next add the following code to "Main.as":

    
    
    package  {
    	import flash.display.Sprite
    	import flash.events.Event;
    	import KeyObject;
    	public class Main extends Sprite{
    		private var key:KeyObject;
    
    		public function Main() {
    			addEventListener(Event.ADDED_TO_STAGE,setupKeyObject);
    		}
    
    		function setupKeyObject(e:Event){
    			key = new KeyObject(stage);
                stage.addEventListener(Event.ENTER_FRAME,movePlayer);
    		}
    
    		function movePlayer(e:Event){
    			if(key.isDown(key.LEFT)){
    			   player.x -= 5;
    			   }
    			if(key.isDown(key.RIGHT)){
    			   player.x +=5;
    			   }
    			if(key.isDown(key.DOWN)){
    			   player.y +=5;
    			   }
    			if(key.isDown(key.UP)){
    			   player.y -=5;
    			   }
    
    			if(player.y<0){
    				player.y =0;
    			}
    			if(player .y > (stage.stageHeight - player.height)){
    				player.y = stage.stageHeight - player.height;
    			}
    			if(player.x<0){
    				player.x = 0;
    			}
    			if(player.x > (stage.stageWidth - player.width)){
    				player.x = stage.stageWidth - player.width;
    			}
    		}
    	}
    
    }
    

    Here we set up our package and import the classes we will be using. Next we set up the key variable as type KeyObject, and within our Main constructor we add an ADDED_TO_STAGE Event Listener. This gets called when the movie is fully loaded and the stage is ready.

    Inside the setupKeyObject function, we set the key variable to be a new instance of the KeyObject class and add an ENTER_FRAME Event Listener to the stage.

    Within the movePlayer function we check which key is being pressed by using key.isDown() and move our player accordingly.

    Finally, we check to see whether the object has moved outside the bounds of the stage, and if it has we put it back just inside the stage.


    Conclusion

    Using Senocular's KeyObject class makes it dead simple to move your game characters! I hope this tutorial has helped; thanks for reading.


  3. Kah Shiu Chong says:
    September 27, 2011 at 4:42 am

    Picturing animation in terms of vectors is intuitive, but understanding vector mathematics is a pain. In this tutorial, I hope to ease that pain and provide a solution to animation problems using a custom written Vector2D class. We will look at some fundamental concepts of linear kinematics in the Eulerian approach: displacement, velocity and acceleration. Then, we’ll build a simple application with it.


    Final Result Preview

    Let's take a look at the final result we will be working towards. Click on the Flash panel below and control the arrowhead by pressing the four directional keys.


    Step 1: Vector Quantity

    All vector quantities have two components: magnitude and direction.

    Image of vector quantity.

    Step 2: Change in Vector Quantity

    A change in vector quantities refers to one of these cases:

    1. Change in direction
    2. Change in magnitude
    3. Change in both magnitude and direction
    Image of vector quantity.

    Step 3: Displacement as a Vector Quantity

    Displacement, velocity and acceleration are vector quantities. Their definitions are as follows:

    • Displacement – Vector of the shortest path pointing from origin to destination. I define origin as point (0, 0) and destination as the particle's location relative to this point. Basically, it refers to the Cartesian Coordinate system as implemented by Flash.
    • Velocity – Velocity is the change of displacement over time.
    • Acceleration – Acceleration is the change of velocity over time.

    The animation below shows displacement as we are going to implement in Flash later.


    Step 4: Velocity as a Vector Quantity

    Velocity is illustrated by the animation below. Note velocity is constant, which means acceleration is absent in this scenario. If velocity is zero, displacement will remain constant throughout.


    Step 5: Acceleration as a Vector Quantity

    Acceleration is illustrated by the animation below. Note: kinematics implies constant acceleration. If acceleration changes over time, it falls under the topic of dynamics. Dynamics is the study of forces that cause of acceleration to vary over time. One such force is gravity, and I’ve written a post on animating that.


    Step 6: Start Building a Projectile

    Now that you have gotten a brief understanding of linear kinematics quantities and able to related them to vectors, we can start building our Projectile class. We would like the projectile be able to capture all these quantities: displacement, velocity and acceleration – so that it can be manipulated on each frame.

    Below is the data we shall record in our Projectile class:

    
    
    private var displace:Vector2D;
    private var velo:Vector2D;
    private var acc:Vector2D;
    

    Step 7: Initialize Projectile

    Upon initiation of this Projectile class, we shall initialise the mentioned variables and draw its graphical representation.

    
    
    public function Projectile()
    {
    	//draw graphics
    	this.draw();
    
    	//init all vector quantities
    	displace = new Vector2D(this.x, this.y);
    	velo = new Vector2D(0, 0);
    	acc = new Vector2D(0, 0);
    }
    
    protected function draw():void
    {
    	//drawing the arrowhead
    	var height:Number = 30;
    	var width:Number = 60;
    	graphics.beginFill(0x0000FF);
    	graphics.moveTo(0, 0);
    	graphics.lineTo(width / -3, height / -2);
    	graphics.lineTo(width / 2, 0);
    	graphics.lineTo(width / -3, height / 2);
    	graphics.lineTo(0, 0);
    	graphics.endFill();
    }
    

    Step 8: Accessors of Vector Quantities

    The following are accessors of our private variables – displace, velo, acc – in the Projectile class.

    
    
    public function setDisp(mag:Number, angle:Number):void
    {
    	displace.redefine(mag, angle);
    }
    
    public function getDisp():Vector2D
    {
    	return displace;
    }
    
    public function setVelo(mag:Number, angle:Number):void
    {
    	velo.redefine(mag, angle);
    }
    
    public function getVelo():Vector2D
    {
    	return velo;
    }
    
    public function setAcc(mag:Number, angle:Number):void
    {
    	acc.redefine(mag, angle);
    }
    
    public function getAcc():Vector2D
    {
    	return acc
    }
    

    Step 9: Updaters of Vector Quantities

    Upon refreshing every frame, we need to update velocity (using acceleration) and update displacement (using the said velocity). This can be achieved using the following functions. For a thorough explanation on Vector addition, do visit this great post from Daniel Sidhon.

    
    
    public function applyVelo():void
    {
    	this.displace = this.displace.add(velo);
    }
    
    public function applyAcc():void
    {
    	this.velo = this.velo.add(acc);
    }
    
    //update sprite's position by displacement.
    public function animate():void
    {
    	this.x = this.displace.x;
    	this.y = this.displace.y;
    }
    

    Step 10: Updater for Sprite'S Orientation

    We will also need to update the orientation of the Sprite. This can be achieved through the rotation property of Sprite.

    
    
    public function orient():void
    {
    	this.rotation = Math2.degreeOf(velo.getAngle());
    }
    

    I have also implemented a Math2 static class, in which I’ve written a function to easily convert back and forth from the angle’s units of degrees and radians.

    
    
    public static function radianOf (deg:Number):Number
    {
    	return deg/180*Math.PI;
    }
    
    public static function degreeOf (rad:Number):Number
    {
    	return rad/Math.PI*180;
    }
    

    Step 11: The Main Class

    Now that we have established our Projectile and Math2 class, we can start to code our Main class. We will need a Vector2D class as well although thorough explanation is not included due to the aforementioned article on Vectors by Daniel Sidhon. I assume readers understand the Vector2D class after reading it. However, if clarifications are needed, do prompt me with your queries.

    First of all, we need to know private variables of this class.

    
    
    private var b1:Projectile;
    
    //keypress flags
    private var UP:Boolean = false;
    private var DOWN:Boolean = false;
    private var LEFT:Boolean = false;
    private var RIGHT:Boolean = false;
    

    Step 12: Initializing Main

    Upon initialization of Main, function init will be launched. This function will create a new Projectile and set its initial velocity. Then, listeners to events will be assigned.

    
    
    private function init(e:Event = null):void
    {
    	removeEventListener(Event.ADDED_TO_STAGE, init);
    	// entry point
    
    	b1 = new Projectile();
    	stage.addChild(b1);
    
    	//setting initial velocity
    	b1.setVelo(5, Math2.radianOf(30));
    
    	//setting event listeners
    	b1.addEventListener(Event.ENTER_FRAME, proj_enterFrame);
    	stage.addEventListener(KeyboardEvent.KEY_DOWN, handle_keyDown);
    	stage.addEventListener(KeyboardEvent.KEY_UP, handle_keyUp);
    }
    

    Step 13: Keyboard Event Listeners

    I have defined user control as keypresses of Up, Left, Down and Left arrow keys. Upon pressing and releasing those keys, flag variables of Main (Step 11) will be turned true and false. Based on these flags, the Vector quantities will be manipulated on every frame. Note as well I have divided controls into horizontal and vertical axis manipulators.

    
    
    private function handle_keyDown(e:KeyboardEvent):void
    {
    	if (e.keyCode == Keyboard.UP) UP = true;
    	else if (e.keyCode == Keyboard.DOWN) DOWN = true;
    
    	if (e.keyCode == Keyboard.LEFT) LEFT = true;
    	else if (e.keyCode == Keyboard.RIGHT) RIGHT = true;
    }
    
    private function handle_keyUp(e:KeyboardEvent):void
    {
    	if (e.keyCode == Keyboard.UP) UP = false;
    	else if (e.keyCode == Keyboard.DOWN) DOWN = false;
    
    	if (e.keyCode == Keyboard.LEFT) LEFT = false;
    	else if (e.keyCode == Keyboard.RIGHT) RIGHT = false;
    }
    

    Step 14: EnterFrame Event Listeners

    Upon refresh of each frame the following code will be executed. It is long, but don't worry; just read on.

    
    
    private function proj_enterFrame(e:Event):void
    {
    	//define acceleration
    	var accMag:Number = 0.1;
    	if (UP) {
    		b1.setAcc(accMag, Math2.radianOf(-90));
    		b1.applyAcc();
    	}
    
    	else if (DOWN) {
    		b1.setAcc(accMag, Math2.radianOf(90));
    		b1.applyAcc();
    	}
    
    	if (LEFT) {
    		b1.setAcc(accMag, Math2.radianOf(180));
    		b1.applyAcc();
    	}
    
    	else if (RIGHT) {
    		b1.setAcc(accMag, Math2.radianOf(0));
    		b1.applyAcc();
    	}
    
    	//decelerate as nothng is pressed to simulate friction.
    	if (UP + DOWN + LEFT + RIGHT == 0) {
    		var currentVeloMag:Number = b1.getVelo().getMagnitude();
    		var currentVeloAng:Number = b1.getVelo().getAngle();
    
    		if(currentVeloMag > 1){
    			b1.setAcc(accMag * -1, currentVeloAng);
    			b1.applyAcc();
    		}
    	}
    
    	b1.applyVelo();
    
    	//restricting sprite to borders of the stage
    	b1.getDisp().x = Math2.implementBound(0, stage.stageWidth, b1.getDisp().x);
    	b1.getDisp().y = Math2.implementBound(0, stage.stageHeight, b1.getDisp().y);
    
    	b1.animate();
    	b1.orient();
    }
    

    Step 15: Update Motion

    Updating the motion should be done in the following order:

    1. Define new acceleration according to user keypress.
    2. Using acceleration, update current velocity.
    3. Using current velocity, update current displacement.
    4. Refine displacement to keep object inside boundaries.

    I’ve highlighted the codes for easy identification of these steps.

    
    
    private function proj_enterFrame(e:Event):void
    {
    	//define acceleration
    	var accMag:Number = 0.1;
    	if (UP) {
    		b1.setAcc(accMag, Math2.radianOf(-90));
    		b1.applyAcc();
    	}
    
    	else if (DOWN) {
    		b1.setAcc(accMag, Math2.radianOf(90));
    		b1.applyAcc();
    	}
    
    	if (LEFT) {
    		b1.setAcc(accMag, Math2.radianOf(180));
    		b1.applyAcc();
    	}
    
    	else if (RIGHT) {
    		b1.setAcc(accMag, Math2.radianOf(0));
    		b1.applyAcc();
    	}
    
    	//decelerate as nothing is pressed to simulate friction.
    	if (UP + DOWN + LEFT + RIGHT == 0) {
    		var currentVeloMag:Number = b1.getVelo().getMagnitude();
    		var currentVeloAng:Number = b1.getVelo().getAngle();
    
    		if(currentVeloMag > 1){
    			b1.setAcc(accMag * -1, currentVeloAng);
    			b1.applyAcc();
    		}
    	}
    
    	b1.applyVelo();
    
    	//restricting sprite to borders of the stage
    	b1.getDisp().x = Math2.implementBound(0, stage.stageWidth, b1.getDisp().x);
    	b1.getDisp().y = Math2.implementBound(0, stage.stageHeight, b1.getDisp().y);
    
    	b1.animate();
    	b1.orient();
    }
    

    Step 16: Slowing Down Motion

    You may find that there are other functions slotted in between these highlighted codes. What are they? One is to apply another vector to slow down our projectile as the user does not press on any keys. This is applied before we add velocity to our displacement.

    
    
    //decelerate as nothng is pressed to simulate friction.
    if (UP + DOWN + LEFT + RIGHT == 0) {
    	var currentVeloMag:Number = b1.getVelo().getMagnitude();
    	var currentVeloAng:Number = b1.getVelo().getAngle();
    
    	if(currentVeloMag > 1){
    		b1.setAcc(accMag * -1, currentVeloAng);
    		b1.applyAcc();
    	}
    }
    

    Step 17: Stay Inside

    The next one is to restrict our projectile to always stay on the stage, otherwise it will fly out of the screen. Again, implementBound is a function I’ve included in the Math2 static class. Given an upper bound, lower bound and a random value, implementBound will return a value that is within the boundaries.

    After applying this constraints onto our displacement (and only after that), we update the Sprite's position with this displacment value.

    
    
    //restricting sprite to borders of the stage
    b1.getDisp().x = Math2.implementBound(0, stage.stageWidth, b1.getDisp().x);
    b1.getDisp().y = Math2.implementBound(0, stage.stageHeight, b1.getDisp().y);
    

    Step 18: Orient Sprite

    Before we leave this sprite as it is, we should orient it so that it always points in the position it's heading using function orient.


    Step 19: Get Set and Go!

    Now everything is set to go. As you launch this piece by pressing on Ctrl + Enter, you will see an arrow that gradually slows down as it heads diagonally down the screen. Press on the four directional keys to move the arrow about. Don't worry about losing your arrow; it'll stay inside your view.


    Conclusion

    This article should get you familiar with using vectors to animate motion. Once you have understood kinematics, do proceed to read up on my post on dynamics. Let me know how it goes. Terima Kasih.


  4. Activetuts+ Editor says:
    September 27, 2011 at 4:44 am

    Fans of the Activetuts+ Facebook page can access a new bonus tutorial, this month covering Flash’s underrated Graphic symbol!


    Introduction

    I first began using Flash since version MX. And through all the enhancements and added features in every release, one thing that has remained constant is the graphic symbol. But what has also remained constant, surprisingly enough, is how many Flash users don’t know what the graphic symbol actually does. Somewhere along the line, this symbol has received a bad rap as being totally useless.

    I can’t tell you how many articles and tutorials I have come across on how to use symbols in Flash that immediately dismiss the graphic symbol as having no practical purpose, relegating it as just a step above grouping items. This article will attempt to dispel this myth by showing that the graphic symbol actually has some pretty cool and convenient features and knowing how and when to utilize them is a nice tool to have when you’re creating animations in Flash.

    So if you ever wondered what exactly the purpose of the graphic symbol is and why the heck Adobe continues to keep it in Flash, this article is for you.

    Facebook Fan Bonus

    Download This Fan Bonus Now!

    All you have to do is Like us…


    Not On Facebook?

    Don’t worry, the tutorial will be posted on Activetuts+ in a month’s time!


  5. José Campos says:
    September 27, 2011 at 5:24 am

    In this tutorial I will walk you through some of the uses of the Twitter REST API, and how you can use it to create a game that not only displays real-time Tweets, but uses them to generate objects the player can interact with.

    Before you read this tutorial, I recommend that you read the AS3 101 sessions by Dru Kepple, Understanding JSON, Understanding the Game Loop – Basix, Greensock Tweening Platform sessions and maybe some design and animation tutorials.


    Final Result Preview

    Let’s take a look at the final result we will be working towards:


    Step 1: Let’s Get the Assets Ready

    Before we get started we will need to set up some assets; we are building a game, so you might want to make it look pretty :-) . We will need buttons for New Game, Instructions, Menu and Tweet (for the player’s score); we will also need a background, some birds, the golden egg and the cracked egg. Besides all that we will need some misc assets such as the loading message, the Tweet message, a “follow me” button, the instructions window and the bar where you will display your Tweets.

    Step 1: Let's get the assets ready

    Step 2: Let’s Create Some Classes

    For this tutorial we will be working with some classes, if you are not familiar with classes you should take a look at the How to Use a Document Class in Flash tutorial.

    We will need a Main class which will be our main brain, that’s the one you will link to your FLA file. Besides that one, we will need a Game class which will handle the game logic of the game and do most of the work. Since games have events that you need to listen to we will create a class named GameEvent which we will use to communicate with our main class. We will also need an Egg class which will hold the data of the Tweet, the kind of egg that it will be, and some other things that we will need later on. And we will need a TweetHolder class which we will link to a movie clip on the library so we can autosize and add some properties to the Tweet that we will show. All of those classes will go to our com folder which needs to be right next to our FLA file.

    Main.as

    
    
    package com {
    
    	import flash.display.*;
    
        // Extends MovieClip cause this will be linked our FLA file
    	public class Main extends MovieClip {
    
            public function Main()
            {
            	// Here we will add our code :-)
            }
        }
    }
    

    Game.as

    
    
    package com {
    
    	import flash.display.*;
    
    	public class Game extends Sprite {
    
            public function Game()
            {
            	// Here we will add the logics for our game
            }
        }
    }
    

    GameEvent.as

    
    
    package com {
    
    	import flash.events.*;
    
        // This will be our custom event so it will extend Event
    	public class GameEvent extends Event {
    
        	// Here we will store the parameters that we will receive, so that we can use them later on, that's why it's public
        	public var parameters:String;
    
            // Here we add the params since we will use it later on to share information between classes
    		public function GameEvent(type:String = "Default", params:String=null, bubbles:Boolean = false, cancelable:Boolean = false)
    		{
            	// We need to initialize our super so we get all its properties
            	super(type, bubbles, cancelable);
            }
        }
    }
    

    Egg.as

    
    
    package com {
    
    	import flash.display.*;
    
        // This will be our custom event so it will extend Event
    	public class Egg extends Event {
    
    		public function Egg()
    		{
            	// Here we will add the logics for our eggs
            }
        }
    }
    

    TweetHolder.as

    
    
    package com {
    
    	import flash.display.*;
    
        // This will be our custom event so it will extend Event
    	public class TweetHolder extends Event {
    
    		public function TweetHolder()
    		{
            	// Here we will add the logics for our TweetHolder
            }
        }
    }
    

    Step 3: Arrange the Menu

    It’s time to start the fun! Place all our menu assets, place your new game button on stage, create the title for your game, add the instructions as well as the instructions button. Once you have all that on stage assign an instance name to each of them since we will need to refer to them in our Main class.

    Step 3: Arrange the menu

    Step 4: Prepare TweenLite

    For this tutorial we will be using TweenLite from GreenSock which you can download HERE (click AS3, download the ZIP file containing it, then unzip it and copy the file named greensock.swc to the folder where you have your FLA file).

    When you have the SWC file right next to your FLA we will need to link it to our FLA so click Edit on the Properties panel of your file:

    Step 4: Prepare TweenLite

    Then click Settings right next to ActionScript 3.0, then the +, and enter “./greensock.swc”

    Step 4: Prepare TweenLite

    After that we are ready to start working in our Main class.


    Step 5: Showing the Instructions

    To show the instructions of the game we will need to have already created a movie clip which will contain the instructions with the instance name of instructions_content and the button that will summon it with the instance name of instructions_btn. Besides that we will take the time to make everything act as a button.

    We will use just one function to make the instructions show and hide so we will need a variable that will tell us whether the instructions are already being displayed; we will call that variable showingInstructions.

    
    
    package com {
    
        // import what we need to animate the objects
    	import com.greensock.TweenLite;
    	import com.greensock.easing.*;
    
    	import flash.display.*;
    	import flash.events.*;
    
    	public class Main extends MovieClip {
    
            // variable that we will use to know if the instructions are being displayed
            // set to false since the first position of the instructions will be out of frame
    		private var showingInstructions:Boolean = false;
    
    		public function Main() {
    			this.addEventListener(Event.ADDED, init);
    		}
    
    		private function init(e:Event):void
    		{
    			this.removeEventListener(Event.ADDED, init);
    
    			// set objects to act like button and get the pointer hand
    			instructions_btn.buttonMode = true;
    			instructions_content.close_btn.buttonMode = true;
    
                // we will call the function instructionsHandler when  the
    			instructions_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
                instructions_content.close_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
    		}
    
            private function instructionsHandler(e:MouseEvent):void
    		{
            	// we ask if the instructions are being showed
    			if(showingInstructions)
    			{
                	// if they are we will want to send them out of frame and tell the game that is not being showed
    				TweenLite.to(instructions_content, .4,{y:600, ease:Cubic.easeIn});
    				showingInstructions = false;
    			} else {
                	// if it's not then we will animate it into stage and tell that it's being showed
    				TweenLite.to(instructions_content, .4,{y:364, ease:Cubic.easeOut});
    				showingInstructions = true;
    			}
    		}
    	}
    }
    

    Step 6: Follow Me Button

    Since you are a developer and you might want users to get in touch with you a “follow me” button sounds like a good idea – so let’s make your button send the users to your twitter profile; we will do this by like so:

    
    
    private function init(e:Event):void
    {
        this.removeEventListener(Event.ADDED, init);
    
        // set objects to act like button and get the pointer hand
        instructions_btn.buttonMode = true;
        followMe_btn.buttonMode = true;
        instructions_content.close_btn.buttonMode = true;
    
        // we will call the function instructionsHandler when  the
        instructions_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
        instructions_content.close_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
        followMe_btn.addEventListener(MouseEvent.CLICK, followMeHandler);
    }
    

    The we will need to create our handler which will be called followMeHandler as we wrote when we declared the listener:

    
    
    // this function will receive a MouseEvent object which we will call "e"
    private function followMeHandler(e:MouseEvent):void
    {
    	// You will need to change jscamposcr for your username, twitter will take care of the rest
        navigateToURL(new URLRequest("http://www.twitter.com/jscamposcr&quot ;) , "_blank");
    }
    

    Step 7: Prepare the Stage for a New Game

    When you have your menu, the instructions and the “follow me” button working it’s time to get your hands dirty and start the hard work – but first we will need to prepare the area with the right objects to start the game. This we will do it by moving out all the objects of the menu, including the instructions.

    First let’s add a click listener to the New Game button that we have in our stage, and then let’s create a function that will clean up the stage.

    
    
    private function init(e:Event):void
    {
        this.removeEventListener(Event.ADDED, init);
    
        // set up listeners, positions, visibility, etc
        newGame_btn.buttonMode = true;
        instructions_btn.buttonMode = true;
        followMe_btn.buttonMode = true;
        menu_btn.buttonMode = true;
        instructions_content.close_btn.buttonMode = true;
    
        newGame_btn.addEventListener(MouseEvent.CLICK, startGame);
        instructions_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
        instructions_content.close_btn.addEventListener(MouseEvent.CLICK, instructionsHandler);
        followMe_btn.addEventListener(MouseEvent.CLICK, followMeHandler);
    }
    

    Next we will take all our objects out of the stage in the function startGame

    
    
    private function startGame(e:* = null):void
    {
        TweenLite.to(newGame_btn, .3, {x:-200, ease:Quad.easeIn});
        TweenLite.to(instructions_btn, .3, {x:500, ease:Quad.easeIn});
        TweenLite.to(followMe_btn, .3, {y:650, ease:Quad.easeIn});
    
        // we will need to hide the instructions if they are being desplayed
        if(showingInstructions)
        {
            TweenLite.to(instructions_content, .3,{y:600, ease:Quad.easeIn});
            showingInstructions = false;
        }
    }
    

    Now we need to add a menu button and a score text field, we will call the menu button menu_btn and the score will be called score_text and it will be a dynamic text field. Don’t forget to embed the font; for this I will embed Verdana Bold by clicking on Embed and adding the characters we will need.

    Step 7: Cleaning up the stage for a new game

    Then add both objects at the top of the stage but out of it since we wont need them in our first frame, then we will add two lines that will animate both of them on our startGame function:

    
    
    private function startGame(e:* = null):void
    {
        TweenLite.to(newGame_btn, .3, {x:-200, ease:Quad.easeIn});
        TweenLite.to(instructions_btn, .3, {x:500, ease:Quad.easeIn});
        TweenLite.to(followMe_btn, .3, {y:650, ease:Quad.easeIn});
    
        TweenLite.to(menu_btn, .3,{y:0, delay:.2, ease:Quad.easeOut});
    	TweenLite.to(score_text, .3,{y:10, delay:.2, ease:Quad.easeOut});
    
        if(showingInstructions)
        {
            TweenLite.to(instructions_content, .3,{y:600, ease:Quad.easeIn});
            showingInstructions = false;
        }
    }
    

    Now let’s give the user the chance to go back to the menu by adding a function to the menu button that we just added; we will call this one goToMenu and we will call it when the user clicks on the menu_btn. For that, we will add an event listener in our start game function:

    
    
    private function startGame(e:* = null):void
    {
        TweenLite.to(newGame_btn, .3, {x:-200, ease:Quad.easeIn});
        TweenLite.to(instructions_btn, .3, {x:500, ease:Quad.easeIn});
        TweenLite.to(followMe_btn, .3, {y:650, ease:Quad.easeIn});
    
        menu_btn.buttonMode = true;
    	menu_btn.addEventListener(MouseEvent.CLICK, goToMenu);
        TweenLite.to(menu_btn, .3,{y:0, delay:.2, ease:Quad.easeOut});
    	TweenLite.to(score_text, .3,{y:10, delay:.2, ease:Quad.easeOut});
    
        if(showingInstructions)
        {
            TweenLite.to(instructions_content, .3,{y:600, ease:Quad.easeIn});
            showingInstructions = false;
        }
    }
    

    Now the function that will make things come back:

    
    
    private function goToMenu(e:MouseEvent):void
    {
    	// we disable the event listener
        menu_btn.removeEventListener(MouseEvent.CLICK, goToMenu);
    
    	// we move back all our assets
        TweenLite.to(title, .3, {y:91, delay:.2, ease:Quad.easeOut});
        TweenLite.to(newGame_btn, .3, {x:162, delay:.2, ease:Quad.easeOut});
        TweenLite.to(instructions_btn, .3, {x:162, delay:.2, ease:Quad.easeOut});
        TweenLite.to(followMe_btn, .3, {y:500, delay:.2, ease:Quad.easeOut});
        TweenLite.to(menu_btn, .3,{y:-35, ease:Quad.easeIn});
        TweenLite.to(score_text, .3,{y:-30, ease:Quad.easeIn});
    }
    

    So far the project should look like this:

    We didn’t actually remove the title; we will leave it there while we show a message that says that the Tweets are being loaded.


    Step 8: Create the Needed Events

    We are almost ready to start our game engine, but as part of it we need to be able to communicate with our Main class. We will do this with events, so let’s take our GameEvent and add the type of events that we want to listen to:

    1. When the game has ended: GAME_ENDED.
    2. When the score has changed: SCORE_CHANGE.
    3. When the Tweets that we load are ready to use: TWEETS_READY.
    4. When the Tweets couldn’t be loaded: TWEETS_ERROR.

    So with all that sorted now we need to edit our GameEvent class

    
    
    package com {
    
    	import flash.events.*;
    
    	public class GameEvent extends Event {
    
    		public static const GAME_ENDED:String = "Game Ended";
    		public static const SCORE_CHANGE:String = "Score Change";
    		public static const TWEETS_READY:String = "Tweets Ready";
    		public static const TWEETS_ERROR:String = "Tweets Error";
    
    		public var parameters:String;
    
    		public function GameEvent(type:String = "Default", params:String=null, bubbles:Boolean = false, cancelable:Boolean = false)
    		{
    			super(type, bubbles, cancelable);
    			parameters = params;
    		}
    	}
    }
    

    With our menu and events created we are finally ready to start our game engine


    Step 9: Setting Up a Game Instance

    To get our game working properly we need to instantiate it, add the event listeners, and destroy them when no longer needed; for that we will add some code to the startGame function, the goToMenu function, and a new function we will created called endGame (this one will kill our game instance and remove the event listeners).

    First let’s edit our “start game” function; we will add the next lines to the end of the end of the startGame function.

    
    
    game = new Game();
    game.addEventListener(GameEvent.GAME_ENDED, endGame);
    game.addEventListener(GameEvent.SCORE_CHANGE, changeScore);
    game.addEventListener(GameEvent.TWEETS_READY, addGame);
    game.addEventListener(GameEvent.TWEETS_ERROR, errorHandler);
    

    Since we are using a var called game we will need to declare it at the begining of our class as a private var:

    
    
    private var game:Game;

    In our goToMenu function we will add a call to our endGame function which we will create and add the following code:

    
    
    private function endGame(e:GameEvent = null):void
    {
    	// This will reset the score in case the user starts a new game
        score_text.text = "Score: 0";
        // This will kill our game with the function killGame that we will create inside our game class
        game.killGame();
        // We will remove all our listeners from our game instance
        game.removeEventListener(GameEvent.GAME_ENDED, endGame);
        game.removeEventListener(GameEvent.SCORE_CHANGE, changeScore);
        game.removeEventListener(GameEvent.TWEETS_READY, addGame);
        game.removeEventListener(GameEvent.TWEETS_ERROR, errorHandler);
    
        // If the game has been added then we will fade it out and then we will remove it from stage and memory
        if (game.addedToStage)
        {
            TweenLite.to(game, .4, {alpha:0, onComplete:(function (){game.parent.removeChild(game); game = null})});
        }
        // If not then we will just kill it
        else
        {
            game = null;
        }
    }
    

    With this we will be good to go and work on our Game class


    Step 10: Loading Tweets

    First we will need to declare some variables that we will use later on:

    
    
    // This will hold the information of our Tweets after they are loaded
    private var goldenEggsData:Object;
    private var crackedEggsData:Object;
    // This will hold our eggs
    private var goldenEggsArray:Array = new Array();
    private var crackedEggsArray:Array = new Array();
    // The count of eggs that have been used
    private var goldenEggsCount:int = 0;
    private var crackedEggsCount:int = 0;
    
    // The speed of the eggs while they fall
    private var speed:int = 4;
    // This is the nest that we will use to catch the eggs
    private var nest:Nest = new Nest();
    // This will hold the eggs that are on stage
    private var eggs:Array = new Array();
    // This will hold the tweets that are being displayed
    private var tweetsOnScreen:Array = new Array();
    // This ones are self-explained
    private var score:Number = 0;
    private var difficulty:Number = 3;
    private var ended:Boolean = false;
    
    // This will tell if the key are being holded
    private var rightKey:Boolean = false;
    private var leftKey:Boolean = false;
    
    // MovieClip from the library
    private var tweetsBar:TweetsBar = new TweetsBar();
    // This says if the game has been added to the stage
    public var addedToStage:Boolean = false;
    

    Then we need to tell the user what is going on so we will add a movie clip to the stage and name it loadingTweets; this says that the Tweets are being loaded. We will fade it in within our startGame from our Main class

    Step 11: Starting our game
    
    
    private function startGame(e:MouseEvent):void
    {
        loadingTweets.x = 130;
        loadingTweets.y = 230;
        loadingTweets.alpha = 0;
    
        TweenLite.to(newGame_btn, .3, {x:-200, ease:Quad.easeIn});
        TweenLite.to(instructions_btn, .3, {x:500, ease:Quad.easeIn});
        TweenLite.to(followMe_btn, .3, {y:650, ease:Quad.easeIn});
        TweenLite.to(loadingTweets, .3, {alpha:1, delay: .2});
    
        menu_btn.buttonMode = true;
        menu_btn.addEventListener(MouseEvent.CLICK, goToMenu);
        TweenLite.to(menu_btn, .3,{y:0, delay:.2, ease:Quad.easeOut});
        TweenLite.to(score_text, .3,{y:10, delay:.2, ease:Quad.easeOut});
    
        if (showingInstructions)
        {
            TweenLite.to(instructions_content, .3,{y:600, ease:Quad.easeIn});
            showingInstructions = false;
        }
    
        game = new Game();
        game.addEventListener(GameEvent.GAME_ENDED, endGame);
        game.addEventListener(GameEvent.SCORE_CHANGE, changeScore);
        game.addEventListener(GameEvent.TWEETS_READY, addGame);
        game.addEventListener(GameEvent.TWEETS_ERROR, errorHandler);
    }
    

    And we will fade it out in our endGame function:

    
    
    private function endGame(e:GameEvent = null):void
    {
        score_text.text = "Score: 0";
        game.killGame();
    
        game.removeEventListener(GameEvent.GAME_ENDED, endGame);
        game.removeEventListener(GameEvent.SCORE_CHANGE, changeScore);
        game.removeEventListener(GameEvent.TWEETS_READY, addGame);
        game.removeEventListener(GameEvent.TWEETS_ERROR, errorHandler);
    
        if (game.addedToStage)
        {
            TweenLite.to(game, .4, {alpha:0, onComplete:(function (){game.parent.removeChild(game); game = null})});
        }
        else
        {
            game = null;
    
            loadingTweets.alpha = 0;
            loadingTweets.x = 800;
            loadingTweets.y = 2300;
        }
    }
    

    It’s now time to start the fun and create the actual game! For that we will need Tweets. The main idea of this tutorial is to load Tweets, and we will use the search API from Twitter to do this.

    I recommend you to go and check it out, but for this game we will just use a few of the possible options; we will make two requests and then add the game to the stage, that’s why we didnt add it when it was created, we will first load the Tweets for the golden eggs in our Game function and we will add an event listener when it’s added, where we start the game:

    
    
    public function Game()
    {
        // tweets loader
        var loader:URLLoader = new URLLoader();
        loader.addEventListener(Event.COMPLETE, loadCrackedEggs);
        loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
    
        // construct the URL q = what we are looking for rpp = the amount of tweets that we want
        // If you are going to use complex string in your URL make sure to use the function encodeURI("Your String") and then add it to the URL
        var url:String = "http://search.twitter.com/search.json?lang=en&q=golden%20eggs&rpp=50&quot;;
    
        loader.load(new URLRequest(url));
    
        this.addEventListener(Event.ADDED, init);
    }
    

    For this request we used just lang which is the language for the Tweets that we want to receive given in a ISO 639-1 code; q which is the main word (can be a phrase as well – just make sure to encode the URL) we are looking for; and rpp which is the number of Tweets that we want to receive. If you want to search for more than one thing you can use OR, it still works just fine but isn’t in the new documentation page so I can’t tell if or they are going to stop supporting it (the same for NOT which becomes handy when you are getting too many spam Tweets).

    For even more information about this go to the “using search” page from Twitter.

    When our Tweets for golden eggs are loaded we will load the Tweets for “cracked eggs” in the function loadCrackedEggs and then we will dispatch an event saying that everything is ready for the game to start:

    
    
    private function loadCrackedEggs(e:Event):void
    {
    	// We will declare this variable as a private variable so we can store the data here
    	goldenEggsData = JSON.decode(e.currentTarget.data);
    
        // tweets loader
        var loader:URLLoader = new URLLoader();
        loader.addEventListener(Event.COMPLETE, startGame);
        loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
    
        // construct the URL ors = what we are looking for rpp = the amount of tweets that we want
        var url:String = "http://search.twitter.com/search.json?q=cracked%20eggs&lang=en&rpp=50&quot;;
    
        loader.load(new URLRequest(url));
    }
    

    Once we load the JSON we will convert it into a object variable that we will declare at the begining of our code – to understand a JSON I recommend you read Understanding JSON – to convert it to an Object we will use the as3corelib from Mike Chambers and its function JSON.decode, which will return an object with all the contents of the JSON file.


    Step 11: Starting Our Game

    To start we will create two arrays which will contain the eggs information and for that we will need our class Egg which we created in Step 2; in that class we will store some data and add the graphics for our eggs. To add the graphics we will need to export the graphics for the eggs from the library to use them in our code like this:

    Step 11: Starting our game

    Then we will need to work in our class:

    
    
    package com {
    
    	import flash.display.*;
    	import flash.events.*;
    
    	public class Egg extends Sprite {
    
            // Here we will store what type of egg this one is so the right graphic is used
    		public var type:String;
            // Stores the string text
    		public var tweet:String;
            // Stores the username of the autor of the tweet
    		public var user:String;
            // Stores the URL of the avatar of the user
    		public var userImg:String;
    
    		public function Egg() {
    			this.addEventListener(Event.ADDED, init);
    		}
    
    		private function init(e:Event):void
    		{
    			this.removeEventListener(Event.ADDED, init);
    
                // Here we add the graphic corresponding the the type of egg
                // We use the MovieClips that we exported in our library
    			if(type == "Golden Egg")
    			{
    				var goldenEgg:GoldenEgg = new GoldenEgg();
    				addChild(goldenEgg);
    			} else {
    				var crackedEgg:CrackedEgg = new CrackedEgg();
    				addChild(crackedEgg);
    			}
    		}
    	}
    }
    

    This is all that we will do to our Egg class.

    Now we will work in our startGame function. Here we will go through the object that contains the information of our Tweets, then for each Tweet that we loaded we will create an egg, give it the required information, and then add it to an array so we can use it later on.

    
    
    private function startGame(e:Event):void
    {
        crackedEggsData = JSON.decode(e.currentTarget.data);
    
        for (var i:int = 0; i < goldenEggsData.results.length; i++)
        {
            var goldenEgg:Egg = new Egg();
            goldenEgg.tweet = goldenEggsData.results[i].text;
            goldenEgg.user = goldenEggsData.results[i].from_user;
            goldenEgg.userImg = goldenEggsData.results[i].profile_image_url;
            goldenEgg.type = "Golden Egg";
    
            goldenEggsArray.push(goldenEgg);
        }
    
        for (var x:int = 0; x < crackedEggsData.results.length; x++)
        {
            var crackedEgg:Egg = new Egg();
            crackedEgg.tweet = crackedEggsData.results[x].text;
            crackedEgg.user = crackedEggsData.results[x].from_user;
            crackedEgg.userImg = crackedEggsData.results[x].profile_image_url;
            crackedEgg.type = "Cracked Egg";
    
            crackedEggsArray.push(crackedEgg);
        }
    
        dispatchEvent(new GameEvent(GameEvent.TWEETS_READY));
    }
    

    Step 12: Error Handling

    It can happen that the Tweets can’t be loaded so it’s a good practice to do something about and not just let it happen, that’s why every time we loaded Tweets we added an IOErrorEvent listener, set to call a function named errorHandler. This function will just dispatch an error event so our Main class can handle it:

    
    
    private function errorHandler(e:IOErrorEvent):void
    {
        dispatchEvent(new GameEvent(GameEvent.TWEETS_ERROR));
    }
    

    Then in our FLA we will add a new frame to our loadingTweets movie clip, there you can add your message for the user to know that something went wrong and move to a different frame so that it doesn’t show what it isn’t supposed to. We will display that in the errorHandler class that we set up as listener for TWEET_ERRORs.

    Step 12: Handling errors
    
    
    private function errorHandler(e:GameEvent):void
    {
        loadingTweets.gotoAndStop(2);
    }
    

    Step 13: Initializing Our Game

    Once the Tweets are ready we can initialize it; for this we will create our addGame function in our Main class, and in this function we will add our game to the stage so the init function on our Game class gets triggered, we will animate out our title, and we will move away the animation we had for the user to know that the Tweets were being loaded.

    
    
    private function addGame(e:Event):void
    {
        addChild(game);
    
        TweenLite.to(title, .3, {y:-200, ease:Quad.easeIn});
        loadingTweets.alpha = 0;
        loadingTweets.x = 800;
        loadingTweets.y = 2300;
    }
    

    Then in our init function for the Game class we will create our first bird, and add a nest (which the player will use to catch the eggs) and a black bar (which will hold the Tweets that the user has catched) – so let’s create those movie clips.

    Our nest needs to have graphics and a invisible movie clip that we will use to test collisions with the eggs; the black bar needs just a basic title. We will need to export both of them for AS use.

    Step 13: Initializing our game
    Step 13: Initializing our game
    
    
    private function init(e:Event):void
    {
        this.removeEventListener(Event.ADDED, init);
    
        // We set our varible to true so our Main class knows if it has been added or not
        addedToStage = true;
        // Set up the position, alpha and animation for our nest object
        nest.x = 10;
        nest.y = 497;
        nest.alpha = 0;
        TweenLite.to(nest, .5,{alpha:1});
        addChild(nest);
    
    	// Add, position and anomation for the Tweets bar
        tweetsBar.x = 350;
        tweetsBar.alpha = 0;
        TweenLite.to(tweetsBar, .6,{alpha:1});
        addChild(tweetsBar);
    
    	// This is our main loop which will take care of our game and tell whats going on
        stage.addEventListener(Event.ENTER_FRAME, updateGame);
        // We will move our nest via keys so we will need to listen to keyboards events
        stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
        stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
    
        // We will create our first bird which is the begining of the actual game
        createBird();
    
    	// To make this game a bit interesting we will change the dificulty of our game as the user plays it
        TweenLite.delayedCall(10, changeDifficulty);
    }
    

    With this ready we will now need to work on our birds, our eggs, our Tweets and the main loop for this game.


    Step 14: Creating Our Birds

    Our birds will drop our eggs so they are kind of important! So let’s create them and animate them. In our createBird function we will create a bird, animate it, and decide when the next bird will be created; besides that we will set up the speed of the bird (to give some variety in the difficulty level they will move faster as the game goes on).

    
    
    private function createBird():void
    {
    	// Create a new Bird instance from out library
        var bird:Bird = new Bird();
        // This is the time that will pass before the egg is released
        var time:Number = (Math.random()*1.3)+.5;
    
    	// We will position out bird out of stage and in random Y position so they look a bit more real
        bird.x = -100;
        bird.y = (Math.random()*60) + 50;
    
        // Animates the bird and destroys it after it's done animating
        TweenLite.to(bird, 5, {x: 600, onComplete:killObject, onCompleteParams:[bird]});
    
        addChild(bird);
    
        if (! ended)
        {
        	// We need to tell our bird to release our eggs after a certian time which will be random
       		TweenLite.delayedCall(time, releaseEgg, [bird]);
            // If the game has no ended we need to create a new bird and depending on the difficulty it will come faster
            TweenLite.delayedCall(Math.random()*difficulty, createBird);
        }
        else
        {
            // Since the game has ended we wont need any updates
            stage.removeEventListener(Event.ENTER_FRAME, updateGame);
    
            // If the game has ended we won't want any eggs to be released so we call any calls to that function
            TweenLite.killTweensOf(releaseEgg);
    
            // Besides not letting any eggs come we will delete all the eggs
            if (eggs.length > 0)
            {
                for (var i:int = 0; i < eggs.length; i)
                {
                    killObject(eggs[i]);
                    eggs.shift();
                }
            }
    
            // We will animate out our nest since no more eggs will be catched
            TweenLite.to(nest, .6,{y:700});
    
            // We will show the score and give the user the option to Tweet it
            showTweetScore();
        }
    }
    

    Step 15: Releasing Eggs

    Now that we have birds flying around we need them to drop eggs, so in our releaseEgg function we will do that:

    
    
    private function releaseEgg(b:Bird):void
    {
        var r:Number = Math.random();
        var egg:Egg;
    
    	// Here we choose if our egg will be a golden eggs or a cracked egg, giving a bit more chance to get a golden egg
        if (r > 0.45)
        {
        	// If the user gets a golden egg then we need to assign one egg form our array of golden eggs and refresh the count
            egg = goldenEggsArray[goldenEggsCount];
            goldenEggsCount++;
        }
        else
        {
        	// If the user gets a cracked egg then we need to assign one egg form our array of cracked eggs and refresh the count
            egg = crackedEggsArray[crackedEggsCount];
            crackedEggsCount++;
        }
    
    	// Then we will assign the position of the bird that is going to release it
        egg.x = b.x;
        egg.y = b.y;
    
    	// Then we add it to stage and push it to our eggs array so it gets updated
        addChild(egg);
        eggs.push(egg);
    }
    

    Step 16: Change Difficulty

    Over time the difficulty will change; we already made a call for that to happen in our init function, so now we will make that happen:

    
    
    private function changeDifficulty():void
    {
    	// The first difficulty is set to 3 so if this function is called we will change it so more birds come together and speed up the eggs
        if (difficulty == 3)
        {
            difficulty = 2;
            speed = 5;
    
            // We call this function again so the difficulty chages again
            TweenLite.delayedCall(10, changeDifficulty);
            return;
        }
        if (difficulty == 2)
        {
            difficulty = 1.5;
            speed = 7;
    
            TweenLite.delayedCall(5, changeDifficulty);
            return;
        }
        if (difficulty == 1.5)
        {
            difficulty = 1;
            speed = 8;
    
            TweenLite.delayedCall(5, changeDifficulty);
            return;
        }
        // If the difficulty is set to 1 it means that this function has been called some times and that the 30 seconds of this game are gone so it's time to end this game
        if (difficulty == 1)
        {
            ended = true;
            return;
        }
    }
    

    Step 17: Getting Things Ready to Move

    To move our nest we will use our keyboard and our update loop, so we need to tell our game which key is being pressed, for that we already created a couple of variables but now we will add the functionality that will make our nest move. We already set up a couple of event listeners – one for when a key is down and another for when it is released – in our init function, so now let’s handle those calls. We will need to use keycodes for this, for more information about those you can visit the Quick Tip about the usage of keycodes

    
    
    private function keyDownHandler(e:KeyboardEvent):void
    {
    	// When the left or right key is holded we need to set it's value to true
        // 37 = left
        // 39 = right
    
        if (e.keyCode == 37)
        {
            leftKey = true;
        }
    
        if (e.keyCode == 39)
        {
            rightKey = true;
        }
    }
    
    private function keyUpHandler(e:KeyboardEvent):void
    {
    	// When the left or right key is released we need to set it's value to false
        // 37 = left
        // 39 = right
    
        if (e.keyCode == 37)
        {
            leftKey = false;
        }
    
        if (e.keyCode == 39)
        {
            rightKey = false;
        }
    }
    

    Step 18: Showing Score

    When the time is gone we will give our user the option to see and share their score, for that we will create a movie clip that states the score and gives the option to share it:

    Step 18: Showing score

    Dont forget to assign an instance name to your dynamic text field and to embed the font that you want to use. When your graphic is ready we are good to go and code it; for this we will create a function named showTweetScore in which we will create a new instance of that movie clip, position it, add a message with the score, and give the option to Tweet the score.

    
    
    private function showTweetScore():void
    {
        var tweetMessage:TweetMessage = new TweetMessage();
        tweetMessage.x = 10;
        tweetMessage.y = 270;
        tweetMessage.message_text.text = "You just scored "+score.toString()+" point on Golden Eggs!";
        tweetMessage.embedFonts = true;
        addChild(tweetMessage);
    
        TweenLite.from(tweetMessage, .6, {alpha:0});
    
        tweetMessage.tweet_btn.buttonMode = true;
        tweetMessage.tweet_btn.addEventListener(MouseEvent.CLICK, shareScore);
    }
    

    Step 19: Share Score

    Once the user clicks on the tweet_btn of our message he or shee will be redirected to a page on Twitter with a prewritten message so they can share their score. To do this we will use another call form the Twitter API – the Tweet button API – for more information about it please visit Twitter’s page.

    For this tutorial we will use just three variables: the text; the URL that we want to share; and “via”, which is kind of the bridge that we are using, in this case Activetuts+.

    The URL that we need to send our user to is https://twitter.com/share, there the user will be able to log in and Tweet about our game. To that URL we must append variables like this:

    
    
    private function shareScore(e:MouseEvent):void
    {
    	// We need to encode the string
        var url:String = encodeURI("https://twitter.com/share?text=I just scored "+score.toString()+" points in Golden Eggs!, try to beat me!&url=http://www.jsCampos.com/GoldenEggs&via=envatoactive");
        // We use _blank so the user can come back and keep playing the game without having to load again the game
        navigateToURL(new URLRequest(url), "_blank");
    }
    

    There are some other variables that you can add to your URL, such as recommended accounts and language, but we won’t use those because those are for the Tweet button so are useless for this tutorial. But I recommend you to go check them out, as they might come in handy some day.


    Step 20: Destroy Objects

    Some times when you create too many variables and objects your application might become slow, so we make use of the garbage collector and tell it what to pick up and what to leave for us to use. Once the eggs get out of stage it means that we don’t need them any more (the same is true for our birds) so it’s a good practice to get rid of them. We will do this with a function called killObject which we have called already a few times and we will call later on. This function will clear that object and get rid of it; it will take a sprite since we are just going to kill display objects.

    
    
    private function killObject(ob:Sprite):void
    {
    	// We will remove them from stage and then set them to null so the garbage collector takes care of it
        ob.parent.removeChild(ob);
        ob = null;
    }
    

    Besides those objects we might need to get rid of our game instance; in those cases we will kill all the listeners so we dont waste memory on anything.

    
    
    public function killGame():void
    {
        if(addedToStage)
        {
            stage.removeEventListener(Event.ENTER_FRAME, updateGame);
            stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
            stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
        }
    }
    

    Step 21: Our Game Cycle

    Our cycle will be one of the most important functions; this will take care of everything that is on stage and keep track of everything. The first thing this function will do is move our nest when the user is pressing the right or left key – keeping in mind that there should be limits for it, so the nest doesn’t go out of stage.

    
    
    private function updateGame(e:Event):void
    {
        if (nest.x < 250 && rightKey)
        {
            nest.x +=  5;
        }
    
        if (nest.x > 9 && leftKey)
        {
            nest.x -=  5;
        }
    }
    

    Then we need to take care of our eggs, check whether any have been caught or have moved out of the stage. For that we will need to add the following code to our function:

    
    
    // First we need to check if there are any eggs on stage
    if (eggs.length > 0)
    {
        for (var i:int = 0; i < eggs.length; i++)
        {
        	// if there are we need to move them so they fall
            eggs[i].y +=  speed;
    
            // Then we need to check if any of those has been catched by using hitTestObject with the invisible object inside our nest
            if (eggs[i].hitTestObject(nest.hit))
            {
            	// If one egg has been catched then we need to add or substract points
                if (eggs[i].type == "Golden Egg")
                {
                    score +=  100;
                }
                else
                {
                    score -=  80;
                }
    
    			// Then we need to let our Main class know so the score text is changed
                // We send the score as a parameter of the GameEvent
                var gameEvent:GameEvent = new GameEvent(GameEvent.SCORE_CHANGE,score.toString());
                dispatchEvent(gameEvent);
    
    			// Then we will show out Tweet in out bar using a class that we will create
                // We will assign the values to this Tweet from out egg, that's why that class has those properties
                var tweet:TweetHolder = new TweetHolder();
                tweet.user_text.text = eggs[i].user;
                tweet.tweet_text.text = eggs[i].tweet;
                tweet.userImg = eggs[i].userImg;
                tweet.x = 5;
    
                tweetsBar.addChild(tweet);
    
    			// If there are too many Tweets being showed we will need to hide some
                if (tweetsOnScreen.length > 0)
                {
                	// first we need to make room for out new tweet
                    for (var a:int = 0; a < tweetsOnScreen.length; a++)
                    {
                        tweetsOnScreen[a].y = tweetsOnScreen[a].y - tweet.height;
                    }
    
    				// if our first tweet is going to high then we need to fade it out
                    if (tweetsOnScreen[0].y < 100)
                    {
                    	// We fade it and them we remove it from stage and from our array of Tweets
                        TweenLite.to(tweetsOnScreen[0], .5,{alpha:0, y:"-100", onComplete:tweetsOnScreen[0].parent.removeChild, onCompleteParams:[tweetsOnScreen[0]]});
                        tweetsOnScreen.shift();
                    }
    
    				// If the new tweet is too long the next one might be too high as well so we need to check and apply the same process
                    if (tweetsOnScreen[0].y < 100)
                    {
                        tweetsOnScreen[0].parent.removeChild(tweetsOnScreen[0]);
                        tweetsOnScreen.shift();
                    }
                }
    
    			// After everything is ready we need to add our new Tweet to our array of tweets
                tweetsOnScreen.push(tweet);
    
                tweet.alpha = 1;
    
                tweet.y = 600 - tweet.height - 10;
    
    			// after we are done it's time to kill that egg
                killObject(eggs[i]);
                eggs.splice(i, 1);
            }
            // If the Tweet wasn't catched and is out of frame then we should destroy it as well
            else if (eggs[i].y > 600)
            {
                killObject(eggs[i]);
                eggs.splice(i, 1);
            }
        }
    }
    

    Step 22: Creating Tweet Objects

    For our Tweet objects we will first need an object from our library, which we will export, and to which we will assign a new class to handle the data that is pushed. This movie clip will have a backup image in case the user image can’t be loaded, a space for the name of the user who Tweeted it, and a space for the Tweet content.

    Step 22: Creating Tweet objects

    When you create your graphics don’t forget to embed the font that you are using.

    The class that we are going to create will fill the data, resize the text fields, load the publisher’s avatar and give the user the posibility to click on the tweet and go to the publisher’s profile:

    
    
    package com {
    
    	import flash.display.*;
    	import flash.events.*;
    	import flash.net.*;
    
    	public class TweetHolder extends MovieClip {
    
    		// This will hold the URL of the image so it can be loaded
    		public var userImg:String;
    
    		public function TweetHolder() {
    			this.addEventListener(Event.ADDED, init);
    		}
    
    		private function init(e:Event):void
    		{
            	// As we did in our Game class we first added the data and then added this to the stage
    			this.removeEventListener(Event.ADDED, init);
                // When it's added it resizes the text fields so no space is wasted
    			tweet_text.autoSize = "left";
    			hit.height = tweet_text.height + tweet_text.y;
    
                // Then we load the image and call a function if the image is loaded or is we get an error
    			var loader:Loader = new Loader();
    			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, addImage);
    			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
    			loader.load(new URLRequest(userImg));
    
                // We finally make this Tweet clickable and add a function to handle the clicks
    			this.buttonMode = true;
    			this.addEventListener(MouseEvent.CLICK, clickHandler);
    		}
    
    		private function clickHandler(e:MouseEvent):void
    		{
            	// To go to the user's profile we just need to add the username to Twitter's URL
    			navigateToURL(new URLRequest("http://www.twitter.com/"+user_text.text), "_blank");
    		}
    
    		private function addImage(e:Event):void
    		{
            	// When the image is added we need to make it look smooth
    			Bitmap(e.currentTarget.content).smoothing = true;
                // Resize it
    			e.currentTarget.content.height = 40;
    			e.currentTarget.content.width = 40;
                // And add it to our Tweet holder
    			addChild(e.currentTarget.content);
    		}
    
    		private function onError(e:Event):void
    		{
            	// If there is an error we just need to catch it
                // Since we already have a backup image we don't need to do anything if the image is not loaded
    			trace("Image couldnt be loaded");
    		}
    	}
    }
    

    When we are done with this class everything should be ready to go.


    Conclusion

    I hope you guys find this tutorial helpful and find great ways to apply what has been taught! For another example of the usage of this you can visit my site home page at JsCampos.com, or check out some other nice games that use Twitter, such as Tweet Land and Tweet Hunt.

    Thanks for your time and I hope you liked it, any feedback is well received.


  6. Dru Kepple says:
    September 27, 2011 at 5:52 am

    In this Quick Tip, we’ll take on run-time Error 2044, the un-handled IO error. It’s actually very simple, but it plagues even experienced developers, so we’ll go in-depth and turn everyone here into IO error ninjas.


    Step 1: Setting up the Problem

    Let’s start by setting up some code in a Flash file that produces error 2044. Create a new AS3 Flash file, and enter this code into the Script panel:

    
    
    var loader:Loader = new Loader();
    loader.load(new URLRequest("some-non-existant.url"));
    

    Go ahead and run the SWF, and you should see this error:

    
    
    Error #2044: Unhandled IOErrorEvent:. text=Error #2035: URL Not Found.
    

    You will see the same error, with a slight variation if we just change Loader to URLLoader, as in below:

    
    
    var loader:URLLoader = new URLLoader();
    loader.load(new URLRequest("some-non-existant.url"));
    

    You should see something like this, only with the file path reflecting your environment:

    
    
    Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: file:////Volumes/Mac%20Pro/Users/dru/Library/Caches/TemporaryItems/non-existant.url
        at Untitled_fla::MainTimeline/frame1()
    

    Step 2: The Accused

    As you might be able to surmise from the fact that Error 2044 crops up with Loader and URLLoader in use, this error has something to do with the loading of external files.

    In fact, the error has something to do with the failure to load an external file. As the fake URL in my code snippets would suggest, the file we are trying to load is having a problem of some sort. Most likely it’s a case of the file being unreachable; this might simply be a mis-spelled URL, or a URL being created dynamically resulting in a bad location, or because the server or network is down at the moment.

    However, Error 2044 is not accusing you loading a bad file. That’s going to happen. We can’t control the network, so a load failure is bound to happen at some point. Error 2044 is accusing you of not being prepared for when that happens.


    Step 3: Good Boy Scouts

    Both Loader and URLLoader are event dispatchers, as you should know from working with them. You need to utilize the Event.COMPLETE event in order to know when a load is ready for you to work with it. If you’re reading this, though, you might not realize that these loading classes also dispatch other events, notably the IOErrorEvent.IO_ERROR event.

    When a Loader or URLLoader encounters a failure, such as described in the previous step, it will dispatch an IOErrorEvent.IO_ERROR event. This is a specialized event for cases such as this. It carries a text property that describes the nature of the error, as seen in the errors we created in the first step; both code snippets produced Error 2044, but the text of each was different (even though it was semantically the same).

    Unlike most events, though, when IOErrorEvents are dispatched, the dispatcher checks for the existence of at least one event listener. If it doesn’t find any, it throws the un-handled IO error.

    So the solution is simple: simply add a listener for the IOErrorEvent.IO_ERROR event to your loader(s). Even if the listener doesn’t do anything, it will at least suppress the Error 2044, by virtue of merely existing.

    
    
    var loader:URLLoader = new URLLoader;
    loader.load(new URLRequest("some-non-existant.url"));
    loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
    
    function onError(e:IOErrorEvent):void {
        // Do nothing
    }
    

    Remember that you add events to the contentLoaderInfo property of Loader objects, not to the Loader directly:

    
    
    var loader:Loader = new Loader();
    loader.load(new URLRequest("some-non-existant.url"));
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
    
    function onError(e:IOErrorEvent):void {
        // Do nothing
    }
    

    However, you should be better prepared than this, like a boy scout; you would ideally determine what an appropriate action to take would be, then start that action in the event handler function. You might decide to load an “image not found” image or a default XML file instead. You might present an alert to the user notifying them that a required resource could not be loaded, and should try again later. Perhaps you also disable parts of your SWF because the required data couldn’t be loaded. You might even fire off a message to a server-side log with details, so that you can look into the situation.


    That Is All

    As I mentioned, this one is pretty easy, really. It’s just a matter of getting in the habit of adding that event handler in the first place, so that you never see Error 2044 again. It won’t prevent resource loading from failing, but it can let you degrade gracefully and recover from the failure as best as you are able.

    Thanks for reading. I’ll see you again shortly in another Debug Quick Tip.


  7. Michael James Williams says:
    September 27, 2011 at 6:28 am

    In this tutorial (the first of a series), you’ll learn the basics of HTML5 game development with JavaScript and the <canvas> element. You don’t need to have any programming experience, or even any HTML experience (apart from this one article). Let’s get started!


    Introduction

    It would be difficult to have missed the “HTML5 vs Flash” articles that have sprung up all over the web, particularly since Steve Jobs’s Thoughts on Flash last year, and Microsoft’s announcement this week that Windows 8′s web browser won’t support Flash on tablets by default. I’m not going to get into that debate here; whatever your opinion, there’s no harm in learning HTML5. Even if you know Flash, it doesn’t hurt to have another tool in your kit.

    This tutorial does not require you know know Flash, or to have had any experience of programming before. In fact, everything that you need to know before you get started is explained in this single article: Get Up to Speed With HTML. That’s it! If you can follow that, you can follow this.

    I’m basing this series on my Flash tutorial series, which in turn was based on an even older Flash tutorial by a guy named FrozenHaddock (to whom I am very grateful for letting me use his ideas). This isn’t a direct port of either tutorial, however; I’ll be completely rewriting the code and the explanations to suit HTML5.

    A couple of notes:

    • Cross-browser compatibility is a real and important issue in web development, but we’re going to be a little selfish and focus on making sure our game works in exactly one browser: Chrome. Rest assured, we will deal with other browsers (including mobile) in other Activetuts+ tutorials, but for the time being, we’ll stick with Chrome, so that we don’t have to split our focus.
    • Clean code is more important in HTML5 than in a lot of other platforms, because the underlying programming language (JavaScript) will let you get away with a lot. So, we’re going to make sure that you get in the habit of writing decent code… eventually. We’ll be a little messy at the start, just to get things rolling and avoid making you scroll through thousands of words on “best practices” before actually getting to do anything.

    In this first part of the tutorial, we’ll just be setting everything up and putting in some very basic game mechanics. Future parts will add multiple spawning enemies, high scores, menu screens, multiple levels, and all that stuff.

    Enough talk – let’s get started!


    Setting Up

    First thing to do is create a .html file. You can use a basic text editor for this, or spend a few hundred dollars on software specifically designed for HTML development; personally, I’d stick with free software for now. Here are three recommendations: TextEdit (for Mac), Notepad++ (for Windows), and Sublime Text 2 (for Windows, OS X, and Linux). Take your pick.

    Create a new file, and enter the following:

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    	</head>
    	<body>
    
    	</body>
    </html>
    

    If you don’t understand what any of that does, read my basic guide to HTML.

    Create a new folder on your hard drive called AvoiderGame, and save this HTML file inside it as game.html. If you load it right now, it’ll just show a blank white page (as you know), so put a paragraph of text in there just to make sure everything’s okay. I’ll add a link to this tutorial, but you could enter anything you like – your name and website, perhaps?

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    	</head>
    	<body>
    		<p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial&quot; rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
    	</body>
    </html>
    

    JavaScript

    Okay, now, you will not be surprised to hear that we will soon be writing some JavaScript – remember, JavaScript lets web pages do things, and that’s exactly what we need for making games. We’ll put all our JavaScript in an external file, in order to keep things tidy, and put this file in a separate folder, to keep things tidier still.

    So, create a new folder, called js inside your AvoiderGame folder. Then, create a new, empty text file, and save it as main.js inside this new AvoiderGame/js/ folder.

    Alter your HTML to refer to this JS file:

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    		<script src="js/main.js"></script>
    	</head>
    	<body>
    		<p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial&quot; rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
    	</body>
    </html>
    

    Note that I haven’t written src="http://active.tutsplus.com/...whatever.../js/main.js", or src="C:\AvoiderGame\js\main.js"; this way, we’re telling the HTML page, “look for a js folder in the same directory as you, and then use the main.js file that’s inside it.” It’s called a relative path.

    If you want to test that this is working, put alert("Working!"); in your JS file, then load the HTML page. If you get a dialog box, everything’s okay.

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    		<script src="js/main.js"></script>
    	</head>
    	<body>
    		<p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial&quot; rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
    	</body>
    </html>
    

    CSS

    While we’re at it, let’s link an external CSS file as well; we can use it to make the text look nicer, and we might need to use CSS in the game later.

    Create a new folder inside AvoiderGame called css, and then create a new, empty text file called style.css inside that. Modify your HTML like so:

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    		<script src="js/main.js"></script>
    		<link rel="stylesheet" href="css/style.css" />
    	</head>
    	<body>
    		<p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial&quot; rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
    	</body>
    </html>
    

    I’m going to modify my CSS file to match some styles we often use on demo pages here at Activetuts+; feel free to copy it, come up with your own, or leave yours blank:

    
    
    body {
    	background: #ffffff;
    	text-align: center;
    	padding: 20px;
    	color: #575757;
    	font: 14px/21px Arial,Helvetica,sans-serif;
    }
    
    a {
    	color: #B93F14;
    }
    
    a:hover {
    	text-decoration: none;
    }
    
    ol {
    	width: 600px;
    	text-align: left;
    	margin: 15px auto
    }
    

    This tutorial isn’t about CSS, so if you don’t understand that, don’t worry about it. (If you’re curious, you can look up the meaning of those CSS attributes on W3Schools.com.)

    Okay, that’s the dull setup out of the way. You can see how the page looks by clicking here, and you can download the entire source so far in a ZIP file here. Let’s create our avatar!


    Get Your Head in the Game

    We need an image that will represent our player’s character in this game. Use whatever you like – a photograph of your face, your Twitter avatar, a picture you’ve drawn – but make sure it has a transparent background, that it’s roughly circular, and that it’s about 30x30px.

    The original tutorial on which this one is based used a skull. I’m not sure why, but I suspect it was an attempt to subvert games’ typical anti-skeleton stance; after all, under our skin, doesn’t every one of us have a skull?

    I’m not one to break with tradition, so I’ll use a skull here too. You can download mine by right-clicking it, if you don’t want to make your own:

    Learn HTML5 With This Simple Avoider Game Tutorial

    And before you ask: yes, I am available for commission.

    Whatever you choose, save it as avatar.png inside a new folder, called img inside AvoiderGame. Your folder structure now looks like this:

    
    
    /AvoiderGame/
    	game.html
    	/css/
    		style.css
    	/js/
    		main.js
    	/img/
    		avatar.png
    

    So how do we get this into our game? If you’ve been paying attention, you’ll probably suggest this:

    
    
    <img src="img/avatar.png" alt="Avatar" />
    

    And, it’s true, that would put the avatar in our page! But it’s not what we’re going to use.

    Canvas

    An img element shows a single image, loaded from a PNG or JPG (or whatever) file. The canvas tag, new to HTML5, can generate an image dynamically, made up of other, smaller images, text, primitive shapes, and so much more, if you desire. Its contents can be modified at any point, so you can give the illusion of motion – or of interaction, if you make the contents change according to what the user does.

    We create a canvas in the same way that we create any other HTML element:

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    		<script src="js/main.js"></script>
    		<link rel="stylesheet" href="css/style.css" />
    	</head>
    	<body>
    		<canvas></canvas>
    		<p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial&quot; rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
    	</body>
    </html>
    

    …though, if you look at this, you won’t be able to see anything there. It’s invisible, so the only effect it has is to move the text down a little.

    With CSS, we can give it an outline so that we can tell it apart from the background. Add this to your CSS:

    
    
    canvas {
    	border: 1px solid black;
    }
    

    Check it out. It’s kinda small, though; let’s make it 400px by 300px (old-school TV dimensions):

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    		<script src="js/main.js"></script>
    		<link rel="stylesheet" href="css/style.css" />
    	</head>
    	<body>
    		<canvas width="400" height="300"></canvas>
    		<p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial&quot; rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
    	</body>
    </html>
    

    That’s better. Now, I said we could add images to the canvas dynamically, so let’s do that next.

    Functions

    Remember in the HTML guide I showed you how to make things happen when you clicked HTML elements? Here’s a quick recap:

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    		<script src="js/main.js"></script>
    		<link rel="stylesheet" href="css/style.css" />
    	</head>
    	<body>
    		<canvas onclick="alert('Clicked the canvas');" width="400" height="300"></canvas>
    		<p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial&quot; rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
    	</body>
    </html>
    

    If you click the canvas, you’ll get a dialog box message. This is because alert() is a JavaScript function: it’s a shortcut to a few lines of code. We can write our own functions in our JS file. Open main.js and enter the following:

    
    
    function alertSeveralTimes() {
    	alert("Hello!");
    	alert("Look, we can run several messages in a row.");
    	alert("Annoyed yet?");
    }
    

    (Delete the original alert("Working!"); if you haven’t already.)

    Do you see how this works? We have created a new function called alertSeveralTimes(), whose contents are inside the curly braces ({ and }). When we tell the browser to run this alertSeveralTimes() function, it will run each of the alerts in turn, one after the other.

    Let’s try it out:

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    		<script src="js/main.js"></script>
    		<link rel="stylesheet" href="css/style.css" />
    	</head>
    	<body>
    		<canvas onclick="alertSeveralTimes();" width="400" height="300"></canvas>
    		<p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial&quot; rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
    	</body>
    </html>
    

    Try it! We’ve effectively bundled up several alert() functions into one bigger function called alertSeveralTimes(), and told it to run whenever the canvas is clicked.

    You might be wondering why the alert("Working!") ran as soon as we opened the page, but the alertSeveralTimes() didn’t, even though they were both in the same place (at the top of main.js). It’s because of that magic keyword function; when the browser sees this, it doesn’t think, “aha, this is some code I must run immediately!”, it thinks, “aha, this is some code I must bundle up into a new function, which I can run later!”

    Anyway. Now let’s make our function do something to the canvas. Making it load an image is a little tricky, so we’ll start with something a bit simpler: changing its size.

    Modifying the Canvas

    One of the most amazing features of JavaScript is its ability to change the HTML of the page. Check this out; modify your JS file so that it contains this:

    
    
    function changeCanvasSize() {
    	gameCanvas.width = 600;
    	gameCanvas.height = 800;
    }
    

    You can probably guess what this is doing: it takes the canvas element, and modifies its width and height attributes (we don’t need to use quotes around numbers in JavaScript, unlike in HTML attributes).

    Except… how does it know that gameCanvas refers to the canvas that we have in our page?

    Well, it doesn’t… yet. We have to make it realise that.

    First, we have to give the canvas element an id (short for “identification”) attribute; this is just a name that we use so that we can refer to it in JavaScript later:

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    		<script src="js/main.js"></script>
    		<link rel="stylesheet" href="css/style.css" />
    	</head>
    	<body>
    		<canvas id="gameCanvas" onclick="alertSeveralTimes();" width="400" height="300"></canvas>
    		<p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial&quot; rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
    	</body>
    </html>
    

    While we’re at it, let’s make the onclick attribute point to our new changeCanvasSize() function:

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    		<script src="js/main.js"></script>
    		<link rel="stylesheet" href="css/style.css" />
    	</head>
    	<body>
    		<canvas id="gameCanvas" onclick="changeCanvasSize();" width="400" height="300"></canvas>
    		<p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial&quot; rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
    	</body>
    </html>
    

    This still isn’t quite enough. We have to let the JavaScript know that it’s dealing with an element from the HTML page (or ‘HTML document’, as it’s more correctly known):

    
    
    function changeCanvasSize() {
    	document.getElementById("gameCanvas").width = 600;
    	document.getElementById("gameCanvas").height = 800;
    }
    

    Now, I know, this doesn’t seem entirely logical. Why is gameCanvas suddenly in quotes? Why do we use document.getElementById("gameCanvas") instead of just, say, getDocumentElement("gameCanvas"), or even document.gameCanvas? I promise, this will all become clear during the tutorial series, but for now, just go with it, please.

    Test out your new code. The canvas resizes itself as soon as you click on it. Awesome!

    Now, I should warn you: programmers are lazy. We hate writing the same code over and over again, and if there’s any way we can reduce the typing required, we’ll take it. So, let me introduce you to a nice shorthand way of referring to the canvas:

    
    
    function changeCanvasSize() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	gameCanvas.width = 600;
    	gameCanvas.height = 800;
    }
    

    See how that works? Just as the function keyword says, “hey, wrap all this code up under the name changeCanvasSize(), please”, the var keyword says, “hey, use the word gameCanvas to refer to the HTML element with an ID of “gameCanvas”, please”. Then (in lines 3 and 4, above), we can use this new shorthand gameCanvas in please of the longer document.getElementById("gameCanvas") – because they refer to the same thing.

    That’s important: we haven’t created a new canvas; we’ve just made gameCanvas refer to the existing canvas element.

    However, it is possible to use var to create something new…

    Click to Skull

    Like I said, we’re moving towards adding an image to the (currently empty) canvas. But before we can do that, we have to load the image. And before we can do that, we have to have something to load the image into.

    Modify your JS like so:

    
    
    function changeCanvasSize() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	gameCanvas.width = 600;
    	gameCanvas.height = 800;
    }
    

    (I’ve added a blank line to clearly separate the var statements from the rest.)

    Here, we’re using the var keyword again – but this time, it says something subtly different: “hey, create a new Image object and use the word avatarImage to refer to it from now on, please.” The Image object is basically like a img element; the crucial difference here is, it’s not in the HTML. We’ve created this brand new element, but it’s nowhere in the HTML; it’s just floating around in the JavaScript aether. I find that a bit weird.

    Just like an img element in the page, this Image is pretty much useless without setting its src, so do that next:

    
    
    function changeCanvasSize() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	gameCanvas.width = 600;
    	gameCanvas.height = 800;
    
    	avatarImage.src = "img/avatar.png";
    }
    

    (Once again I’m using a blank line to keep bits of code that do different things separated from each other (like paragraphs in text), and once again I’m using a relative path to refer to a file’s location.)

    So this is now loading the image, but you’ll have to take my word for it at the moment, since it’s still out there in the aether where we can’t see it. However, we can check its other attributes:

    
    
    function changeCanvasSize() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	gameCanvas.width = 600;
    	gameCanvas.height = 800;
    
    	avatarImage.src = "img/avatar.png";
    	alert(avatarImage.width);
    }
    

    We’re telling it to show us a dialog box containing the value of the width attribute of our image. Check it on your code and see what you get; I get 29, which is exactly right.

    With just one more line of code, we can draw the avatar on the canvas:

    
    
    function changeCanvasSize() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	gameCanvas.width = 600;
    	gameCanvas.height = 800;
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, 0, 0);
    }
    

    Let’s break this down:

    • gameCanvas.getContext("2d"): We don’t actually draw directly on the canvas, we draw onto what’s called a “drawing context”; this lets us determine whether we want to draw in 2D or 3D. Okay, there’s no 3D context at the moment, but this is letting us plan for the future.
    • drawImage(): Pretty straightforward. This is a function that lets us draw an image onto the context of a canvas.
    • avatarImage: This is the image object we’ve got floating around in the aether, remember?
    • 0, 0: These are the coordinates at which we want to draw the image. In school, you’re taught that (0, 0) is the bottom-left of the page; on a computer, it’s the top-left (the x-axis points to the right, and the y-axis points downwards).

    Take a look. It works! (If it doesn’t, remember that you should be viewing this in Chrome; I don’t guarantee that this will work in any other browser.)

    Multiple Skulls

    The drawImage() function works like a potato stamp:

    Learn HTML5 With This Simple Avoider Game Tutorial
    Photo by jimmiehomeschoolmom

    It just takes the contents of the image object and clones them onto the canvas; of course, we’re dealing with pixels, not paint, but you get the idea.

    This means we can add multiple skulls to the canvas, like so:

    
    
    function changeCanvasSize() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	gameCanvas.width = 600;
    	gameCanvas.height = 800;
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, 0, 0);
    	gameCanvas.getContext("2d").drawImage(avatarImage, 100, 50);
    	gameCanvas.getContext("2d").drawImage(avatarImage, 200, 130);
    	gameCanvas.getContext("2d").drawImage(avatarImage, 300, 270);
    }
    

    Check it out, skull party. We can also make the skull appear in a random place each time:

    
    
    function changeCanvasSize() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	gameCanvas.width = 600;
    	gameCanvas.height = 800;
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    }
    

    Math.random() give you a random number between 0 and 1, so Math.random() * 100 gives you a random number between 0 and 100; this means that the coordinates of the new skull are anywhere between (0, 0) and (100, 100). Take a look!

    But hold on – why is there only one skull at a time now? Is it something to do with it being a new function? Does the canvas get cleared every time you run a function?

    No. The canvas is cleared every time you modify its height or width, even if you don’t change either. So, if we change our JS like so:

    
    
    function changeCanvasSize() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    }
    

    …then we can keep adding new skulls.

    In fact, let’s change the name of the function to drawAvatar(), and tidy things up a bit:

    
    
    function drawAvatar() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    }
    

    Don’t forget to change the onclick attribute of canvas in your HTML:

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>HTML5 Avoider Game</title>
    		<script src="js/main.js"></script>
    		<link rel="stylesheet" href="css/style.css" />
    	</head>
    	<body>
    		<canvas id="gameCanvas" onclick="drawAvatar();" width="400" height="300"></canvas>
    		<p>From <a href="http://active.tutsplus.com/tutorials/html5/learn-html5-with-this-simple-avoider-game-tutorial&quot; rel="external">Learn HTML5 With This Simple Avoider Game Tutorial</a>.</p>
    	</body>
    </html>
    

    Okay, now let’s get that avatar moving.


    Adding Interactivity

    I want to make the avatar follow the mouse. We can use the same principle that animators do: if we keep erasing the contents of the canvas, and then re-drawing the avatar at a different position, the avatar will appear to move. So all we have to do is keep redrawing the avatar at the mouse’s coordinates, and we’re set!

    How do we do that, though?

    A Grand Event

    Judging by what we’ve done so far, you might guess that we’d add a onmousemove event attribute to the canvas (which would be triggered every time the user moved their mouse), then make it run drawAvatar(), but specifically at the mouse’s current coordinates. This is inspired, but unfortunately doesn’t really work, simply because it doesn’t offer an easy way to obtain the mouse’s coordinates.

    However, it is very close to what we want to do! Take a look at this:

    
    
    function drawAvatar() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    
    	gameCanvas.addEventListener("mousemove", redrawAvatar);
    }
    

    This does roughly the same thing as the above suggestion; the redrawAvatar() function (which we haven’t written yet) will be called whenever the mouse moves over the canvas. But there’s one big difference.

    Notice how we write redrawAvatar, rather than redrawAvatar() in the code above, whereas in our HTML page, we put drawAvatar() – with “parentheses” (round brackets) – in the onclick event attribute of our canvas. The full reason for that is a little complicated to go into now (though you’ll understand by the end of the series), but it has one very important upshot: it allows us to obtain the mouse’s coordinates.

    When the mouse moves, the browser creates a new object – just like when we created a new Image in our JavaScript earlier. This object has certain attributes that have something to do with the thing that triggered its creation; in this case, because the mouse moved, it contains the coordinates of the mouse. Brilliant!

    So how do we access it? Well, this new object (which is called a MouseEvent, for reasons that you might be able to guess) gets passed to the redrawAvatar() function. Er, but we haven’t written that yet, so let’s do that now. Add this code to your JS file:

    
    
    function drawAvatar() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    
    	gameCanvas.addEventListener("mousemove", redrawAvatar);
    }
    
    function redrawAvatar(mouseEvent) {
    
    }
    

    Aha – this time, the way we define the function is a little different: we’ve added the word mouseEvent in-between those parentheses. This is because we are expecting the browser to pass a MouseEvent object to our new function, just like when we passed the coordinates to the drawImage() function.

    Since we’ve given it a name, we can access the attributes of this new object:

    
    
    function drawAvatar() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    
    	gameCanvas.addEventListener("mousemove", redrawAvatar);
    }
    
    function redrawAvatar(mouseEvent) {
    	alert(mouseEvent.x);
    }
    

    Test this out; you’ll have to click the canvas before anything will happen, because it’s inside that function that we make the browser start paying attention to mouse movements.

    You’ll notice that the dialog box only appears when the mouse moves over the canvas element. You might also notice something odd about the number: it’s too big! I’m getting numbers of over 900, even though the width of the canvas is only 400.

    This is because mouseEvent.x gives the mouse’s x-position from the edge of the page, rather than the edge of the canvas. We can use mouseEvent.offsetX to get the mouse’s x-position from the edge of the canvas:

    
    
    function drawAvatar() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    
    	gameCanvas.addEventListener("mousemove", redrawAvatar);
    }
    
    function redrawAvatar(mouseEvent) {
    	alert(mouseEvent.offsetX);
    }
    

    Much better!

    So, to recap: addEventListener() makes the browser listen for certain events – such as the movement of the mouse – and then run a function when this event is “heard”. The browser creates a new object (like a MouseEvent), and passes it to that function.

    It’s a little hard to wrap your head around, but don’t worry; we’ll be using it a lot, so you’ll get the hang of it!

    Move Your Head

    We’ve nearly got movement. In fact, I recommend you have a go at making the avatar follow the mouse on your own before reading further. You’ll probably come very close!

    There’s one big thing that’ll trip you up, though: the word var – which, you’ll remember, you can use to set a shorthand – only “lasts” within the function in which it was defined.

    This means that if you try to do, say:

    
    
    function drawAvatar() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    
    	gameCanvas.addEventListener("mousemove", redrawAvatar);
    }
    
    function redrawAvatar(mouseEvent) {
    	gameCanvas.width = 400;
    	alert(mouseEvent.offsetX);
    }
    

    …it won’t work, because gameCanvas means nothing outside of drawAvatar()!

    So, if you didn’t get it the first time, have another go.

    My code is here if you want to check yours (click the little triangle):

    
    
    function drawAvatar() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    
    	gameCanvas.addEventListener("mousemove", redrawAvatar);
    }
    
    function redrawAvatar(mouseEvent) {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, mouseEvent.offsetX, mouseEvent.offsetY);
    }
    

    Tada! Oh, wait, dang, I forgot to erase the canvas by changing its width or height. Cool effect, but let’s try that again:

    
    
    function drawAvatar() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    
    	gameCanvas.addEventListener("mousemove", redrawAvatar);
    }
    
    function redrawAvatar(mouseEvent) {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.width = 400;
    	gameCanvas.getContext("2d").drawImage(avatarImage, mouseEvent.offsetX, mouseEvent.offsetY);
    }
    

    Try it out now. Success!

    Wait, What Was That For?

    When you take another look at your code in a few days’ time, you’re likely to have forgotten what a lot of it is for. In particular, I suspect you’ll forget why you need to resize the canvas.

    Fortunately, there’s a way to remind yourself: comments.

    Look at this:

    
    
    function drawAvatar() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    
    	gameCanvas.addEventListener("mousemove", redrawAvatar);
    }
    
    function redrawAvatar(mouseEvent) {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.width = 400;	//this erases the contents of the canvas
    	gameCanvas.getContext("2d").drawImage(avatarImage, mouseEvent.offsetX, mouseEvent.offsetY);
    }
    

    The browser ignores everything on the line after a //. This means you can write whatever you like there, and it won’t be run as code. It’s called an inline comment and is very important. To help get yourself into the habit of commenting your code, go through it now and write comments after each line that you think you might have trouble understanding after a few days’ break.

    Commenting may seem like a waste of time. I think a lot of new programmers assume that when they first start out; it only takes one bad experience with trying to update your own, uncommented code (or worse: someone else’s!) to convince you of its worth, though :)

    Hide the Mouse

    At the moment, you’ve got a big stupid mouse cursor hovering over your avatar:

    Learn HTML5 With This Simple Avoider Game Tutorial

    We can fix this with a little CSS. Modify your stylesheet like so:

    
    
    canvas {
    	border: 1px solid black;
    	cursor: none;
    }
    

    In most browsers, this will make your cursor disappear when it’s on top of the canvas… but not in Chrome.

    Chrome doesn’t support cursor: none;, but it does allow you to replace the cursor with a PNG file of your choice. So, you can create a PNG that’s completely transparent, put it in your img folder, and use that, like so:

    
    
    canvas {
    	border: 1px solid black;
    	cursor: url("../img/transparentcursor.png"), none;
    }
    

    (I’ve had to put ../ at the start of the URL because, in CSS, relative paths are relative to the folder of the CSS file, not the HTML file, and “..” says, “the folder above this one”. Also, I’ve put , none after this, because it means that if any browsers don’t support using PNGs for cursors, they’ll use the none attribute instead. Can you see why I wanted to avoid focusing on cross-browser compatibility?)

    Unfortunately, this doesn’t work either, because if you use a completely transparent PNG, Chrome just shows a solid black rectangle instead. Thanks, Chrome.

    So, instead, I’ve made a 1x1px PNG that’s almost transparent (the single pixel is white, with an opacity of 1%). You can download it here. Copy it to your img folder, then modify your CSS stylesheet:

    
    
    canvas {
    	border: 1px solid black;
    	cursor: url("../img/almosttransparent.png"), none;
    }
    

    Test it out. It does work, after all that effort.


    Make an Enemy

    We’ve accomplished a lot so far, but our avoider game still doesn’t have anything to avoid! The last thing we’ll do, in this part of the series, is create an enemy.

    We need an image to represent this. Draw whatever you like, but make sure that it’s roughly circular, and about 30x30px. I’m going to take my cue from FrozenHaddock again. He picked a smiley face for his game’s enemy; I’m not sure why, but I suspect it was a comment on the over-pervasiveness of smileys in modern conversation; a yearning for the days of emotions over emoticons, where poets would pour their hearts into a single sentence of text, rather than simply typing semicolon close-parenthesis ell oh ell. Or maybe it’s just because smiley faces are easier to draw. Regardless, here’s mine:

    Learn HTML5 With This Simple Avoider Game Tutorial

    Call yours enemy.png and put it in the img directory.

    You can probably figure out how to draw this enemy (unmoving) on the canvas – if so, give it a shot! Once again, I recommend you do this before reading on.

    Here’s my solution (click the little triangle):

    
    
    function drawAvatar() {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
    
    	gameCanvas.addEventListener("mousemove", redrawAvatar);
    }
    
    function redrawAvatar(mouseEvent) {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    	var enemyImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	enemyImage.src = "img/enemy.png";
    	gameCanvas.width = 400;		//this erases the contents of the canvas
    	gameCanvas.getContext("2d").drawImage(avatarImage, mouseEvent.offsetX, mouseEvent.offsetY);
    	gameCanvas.getContext("2d").drawImage(enemyImage, 250, 150);
    }
    

    Your method might be different to mine – that’s okay, as long as it works! But for consistency, please copy my method into your code.

    Note that I keep the var statements at the top of their respective functions. This isn’t strictly necessary, but it keeps things tidy, so I recommend it.

    Besides that, nothing here should surprise you. There’s no particular significance to the coordinates (250, 150) that I’ve chosen.

    Try it out!

    Putting the “Avoid” in “Avoider Game”

    We’re not going to worry about making the enemy move in this part of the tutorial; that topic deserves more space than I can afford it here. But we will check for a collision between the avatar and the enemy!

    First, we’ll do something simpler: we’ll consider a certain area of the screen “off-limits” and pop up a dialog box if the avatar moves into that area.

    Modify your redrawAvatar() function like so:

    
    
    function redrawAvatar(mouseEvent) {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    	var enemyImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	enemyImage.src = "img/enemy.png";
    	gameCanvas.width = 400;		//this erases the contents of the canvas
    	gameCanvas.getContext("2d").drawImage(avatarImage, mouseEvent.offsetX, mouseEvent.offsetY);
    	gameCanvas.getContext("2d").drawImage(enemyImage, 250, 150);
    
    	if (mouseEvent.offsetX < 100) {
    		alert("Too far left!");
    	}
    }
    

    Try it out. If your avatar goes too far to the left side of the screen, the dialog box appears.

    Let’s take a closer look at the code:

    
    
    if (condition) {
    	outcome;
    }
    

    The if statement is a way of checking whether something has happened. It’s made up of two parts: a condition, inside the parentheses, and a result, inside the curly braces. If the condition is true, then the outcome is called.

    In our case, the condition is mouseEvent.offsetX < 100. The < symbol means "less than", and remember that mouseEvent.offsetX is the cursor's horizontal distance from the left edge of the canvas. So, this is checking whether the cursor is within 100 pixels of the left edge of the canvas. If it is, then...

    ...the outcome is run. And in our case, the outcome is alert("Too far left!");, the dialog box function we've used a number of times.

    Make sense? Okay, good, because I'm going to make it more complicated:

    
    
    function redrawAvatar(mouseEvent) {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    	var enemyImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	enemyImage.src = "img/enemy.png";
    	gameCanvas.width = 400;		//this erases the contents of the canvas
    	gameCanvas.getContext("2d").drawImage(avatarImage, mouseEvent.offsetX, mouseEvent.offsetY);
    	gameCanvas.getContext("2d").drawImage(enemyImage, 250, 150);
    
    	if (mouseEvent.offsetX < 100 || mouseEvent.offsetY < 100) {
    		alert("Too far left, or too far up!");
    	}
    }
    

    In this code, we've introduced a new operator: ||. || means (and is pronounced) "or". The if statement therefore reads:

    "If the mouse is within 100 pixels of the left edge of the canvas, OR the mouse is within 100 pixels of the top edge of the canvas, show the dialog box."

    Try this out, and you'll see that you can't get anywhere near the top or the left of the canvas.

    How about this:

    
    
    function redrawAvatar(mouseEvent) {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    	var enemyImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	enemyImage.src = "img/enemy.png";
    	gameCanvas.width = 400;		//this erases the contents of the canvas
    	gameCanvas.getContext("2d").drawImage(avatarImage, mouseEvent.offsetX, mouseEvent.offsetY);
    	gameCanvas.getContext("2d").drawImage(enemyImage, 250, 150);
    
    	if (mouseEvent.offsetX > 150 && mouseEvent.offsetX < 250) {
    		alert("Stay out of the middle!");
    	}
    }
    

    The && operator means (and is pronounced) "and", and > means "greater than". So, our if statement now reads:

    "If the mouse is more than 150 pixels away from the left edge of the canvas AND the mouse is less than 250 pixels away from the left edge of the canvas, show the dialog box."

    Test it out, and you'll see that we effectively have an invisible "stripe" down the middle of the canvas where we can't put our mouse.

    We're not restricted to just using two clauses at once; check this out:

    
    
    function redrawAvatar(mouseEvent) {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    	var enemyImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	enemyImage.src = "img/enemy.png";
    	gameCanvas.width = 400;		//this erases the contents of the canvas
    	gameCanvas.getContext("2d").drawImage(avatarImage, mouseEvent.offsetX, mouseEvent.offsetY);
    	gameCanvas.getContext("2d").drawImage(enemyImage, 250, 150);
    
    	if (mouseEvent.offsetX > 150 && mouseEvent.offsetX < 250 && mouseEvent.offsetY > 100 && mouseEvent.offsetY < 200) {
    		alert("Stay out of the center!");
    	}
    }
    

    We've now effectively drawn a 100x100px box, in the centre of the canvas, where we can't put our mouse.

    Can you see where we're going with this?

    Rather than a 100x100px box in the middle of the canvas, we should use a 30x30px box positioned where our enemy is.

    This is the last thing we're going to do in this part of the tutorial, so once again I recommend you have a go yourself. It's pretty fiddly - you'll probably want to get some paper out to draw the avatar and the enemy and label some coordinates - but you can do it if you use what you've learned so far.

    My solution is below.

    
    
    function redrawAvatar(mouseEvent) {
    	var gameCanvas = document.getElementById("gameCanvas");
    	var avatarImage = new Image();
    	var enemyImage = new Image();
    
    	avatarImage.src = "img/avatar.png";
    	enemyImage.src = "img/enemy.png";
    	gameCanvas.width = 400;		//this erases the contents of the canvas
    	gameCanvas.getContext("2d").drawImage(avatarImage, mouseEvent.offsetX, mouseEvent.offsetY);
    	gameCanvas.getContext("2d").drawImage(enemyImage, 250, 150);
    
    	//my avatar is 30px wide and the enemy is at x=250, so I have to check whether mouseEvent.offsetX is within 30px
    	//either side of x=250 (i.e., from 220 to 280)
    	//similarly, since my avatar is 33px tall, I have to check whether mouseEvent.offsetX is within 33px ABOVE y=150
    	//but since enemy is only 30px tall, I also check whether mouseEvent.offsetX is within 30px BELOW y=150
    	//therefore, I check from (117 to 180)
    	if (mouseEvent.offsetX > 220 && mouseEvent.offsetX < 280 && mouseEvent.offsetY > 117 && mouseEvent.offsetY < 180) {
    		alert("You hit the enemy!");
    	}
    }
    

    Try it out here!


    Next Time

    That's it for the first part of the tutorial. In the next part, we'll get that enemy moving, and we'll add more of them, so that this can start to be a real game!

    In the meantime, why not experiment with what you've learned? You could try adding multiple (unmoving) enemies yourself, perhaps with different graphics. Or you could add several avatars on screen at once, all following the mouse in different ways. What happens if you use something like mouseEvent.offsetX + 100 or 300 - mouseEvent.offsetY in your call to gameCanvas.getContext("2d").drawImage()?

    I hope you've enjoyed this so far. If anything's not clear, please ask about it in the comments :)

    (One other quick note: at the moment, your code should work just fine on your own computer, but won't work if uploaded to the web. My demos work online, because I did a sneaky trick. Don't worry, I'll explain how to solve this in a future part of the tutorial.)


  8. Travis King says:
    September 27, 2011 at 6:54 am

    As a famous British band once sang – we all get by with a little help from our friends. And if you have ever decided to design a kick butt game, who couldn’t use a little help?

    Today we’re going to run down some of the ultra-helpful Unity 3D tools that are available over at ActiveDen. And if this whole Unity 3D thing is new to you, please check out our introduction series on Getting Started with Unity. Now get out there and start designing me some games!


    1. Cave Run 3D Unity Game Starter Kit

    This is a 3D version of my Cave Run Flash Game . Run like crazy, jumping on platforms and avoiding obstacles. Collect as many gems as you can and don’t fall!


    2. Mini Golf Construction Kit

    Mini Golf Construction Kit has everything you need to create a mini golf game.You can create a 18 hole commercial ready game in a day.Package contains over 80 prefabs of course pieces and obstacles, a complete game demo with 6 courses included and a GUI example to help you get started, a setup guide and one video. There are few animated obstacles and one animated course piece.


    3. FPS Starter Pack – Upgrades & Store

    Have you ever wanted to make your own ‘Call of Unity’ FPS ? With this weapon upgrades and store system, along with the base Dastardly Banana FPS Constructor (included), you can! Create varied weapon upgrades, like scopes, secondary weapons, and camouflage, without any coding through the modular upgrades framework! Unlock weapons and upgrades through the store system; just drag the provided Store prefab into your scene and hit play! Add these new features, along with two new fully animated weapon models, to the base Dastardly Banana FPS Constructor and you can make your Unity FPS in no time.


    4. Match-3 new style game starter kit

    This is physics based match-3 style game. It would be helpful for beginners, here is tricky things: locking object’s position and rotation, parenting objects, instantiate particles and change their color to match destroyed ball’s color and much more.


    5. BloodSplatter Prefab

    Includes blood material and particle system blood splatter simulation. Hooray?


    6. Day/Night Cycle

    Component allows you to use realistic Day/Night Cycle in your Projects.


    7. Bowling Game Starter Kit

    The bowing game starter kit will help you to develop bowling games in Unity3d. It’s a bowling game all ready to go!


    8. Local High Score Script pack

    The Local High Score Scripts pack includes everything you need to add basic, local (as in, offline) high score tables to your Unity3d games.


    9. 3D Memory

    3D Memory is a classic memory game. This game is going to help you create any other matching game and high score system with multiple elements. In this case we have name, avatar and time, game is keeping scores of the ten best scores per level. There are 135 images to be matched so you can’t play the same game twice.


    10. UFO3D – Unity Game

    UFO3D is the Unity version of my other game, UFO2D. Move with the mouse, pick up cows and drop them at the portal. Get as many cows as you can before time runs out!


    11. Guitar Unity

    This game starter kit has you on the way to your own guitar reaction game. The included custom editor helps you create new songs, add your own music and design challenging note patterns with just a few simple steps.


    12. Mighty Cannon Shooter Game

    Shoot the targets and try to get as many points as possible! The further you shoot, the more you get.


    13. Spawn Controller

    Spend more time designing and balancing, and less time trying to make things work! With the Dastardly Banana Spawn Controller, designing, configuring, and customizing the way objects spawn in your scene is easy.


    14. Air side-scroller

    Every option is adjustable in this project, you can manipulate with player’s and enemy’s options: movement speed, bullet and rocket shooting speed, bullet resistance, explosion and bullet prefab, sounds etc…


    15. Mech Starter Pack

    This is a Starter Pack that will teach you how to get a head start on creating an advanced 3rd person shooter with amazing graphics, animations, and gameplay. It includes a fully rigged detailed robot mesh known as J3 along with all his necessary animations in fbx format such as run, jump, shoot, as well as strafe. It also has two different enemy types known as an EyeBot and SentryGun to provide J3 with win and losing conditions. Powerups that refill your health, ammo and missles.


    16. Cloudy Night Skybox

    This Skybox is custom made for the Unity environment, pre-packaged and ready for import and use. Easy as importing the package into an existing or new scene.


    17. Unitroids Space Shooter

    Unitroids is a game where you fly a small spaceship through unknown space worlds. Unfortunately, pesky little asteroids are cluttering up your way. You can either avoid them , or shoot them and blow them up. But when they explode, they will split and make things more complicated.


    18. RC Helicopter Simulation

    RC Helicopter Simulation can be used like a helicopter template project. Based on this simulation you can create your own helicopter game in no time. By adjusting helicopter stability control you can choose between simulation style and arcade style game. Package includes PDF help file that will help you get started and a fully commented source code.


    19. Analog Clock for Unity3d

    The whole clock, scripting and all, is neatly contained in an easy-to-use prefab. Just import the .unitypackage and drop it on your scene. All the settings can be modified via the inspector panel – you don’t even need to touch the Javascript.


    20. Level loader (prefab-based level builder)

    The level ‘maker’ script is designed to build a level dynamically from a layout specified within a script file.


    21. Planet Earth Prefab

    This realistic Earth prefab is super easy to work with. Includes stars and sun/camera flare reflections. Also, simply change speed with the speed setting.


    22. Unity 3D Slot Machine Prefab

    New to the Unity catalogue on Active Den, this is a fully working slot machine, modelled after the sort you see standing in a typical Las Vegas casino. You pay, you play, you might even win. Have a look at the preview and see for yourself.


  9. Daniel Sidhion says:
    September 27, 2011 at 7:35 am

    Learn the basics of how FlashPunk works – an amazing library to save you time and help you create the perfect game!


    Final Result Preview

    Let’s take a look at the final result we will be working towards:

    Use the arrow keys to move your character (the blue guy). The red/brown guy is an NPC; the shaded red area is a danger zone, and the green box is a button. You’ll learn how to create all this in this tutorial.


    Step 1: What Is FlashPunk?

    FlashPunk logo

    FlashPunk is an ActionScript 3 library created for the development of Flash games. Basically, it does all the hard work for you and lets you focus entirely on developing your game, rather than on the engine behind it. The best part about it is that you don’t need Flash Pro to work with it: you can do everything with a free code editor like FlashDevelop. Not to mention it’s way faster when it comes to drawing things on screen, since it uses blitting!

    This tutorial will go through all the basics of FlashPunk. After following it, you’ll be ready to make a simple game with this amazing library!


    Step 2: Initializing the Engine

    Begin by downloading the latest version of FlashPunk from the official site (this tutorial uses the version from August 30, 2011). Put the “net” folder, with all its contents, in your “src” folder.

    FlashPunk has a class called Engine. This class is what starts everything in the library. Think of it as a Main class, but with special code to power up all the classes in FlashPunk. In order to use the Engine class, we will modify the Main class a little bit.

    
    
    package
    {
    	import net.flashpunk.Engine;
    
    	[Frame(factoryClass="Preloader")]
    	public class Main extends Engine
    	{
    
    		public function Main():void
    		{
    
    		}
    
    	}
    
    }
    

    Now, our class extends Engine. In Main‘s constructor, we need to make a call to the Engine constructor: this is what sets the important information about the game: width, height, framerate and whether the engine should run at a fixed framerate or not.

    
    
    public function Main():void
    {
    	super(550, 400, 30, false);
    }
    

    There is a function that can (and must be) overridden from the Engine class: the init() function. It will run only once, and will initialize everything to get the game working.

    
    
    override public function init():void
    {
    	trace("The game has started!");
    }
    

    I’m pretty sure everyone wants to put something on the screen and see this engine working! Because of that, the next few steps will cover the very basics of the elements of FlashPunk, adding depth as the tutorial goes on.


    Step 3: Worlds and Entities

    In FlashPunk, there are elements called Worlds and Entities. These are the main elements of the library, and you’ll work with them from the beginning to the very end of your game.

    Worlds are pretty much like what is commonly known as a “screen”. Everything in your game will happen in a world: the main menu is a world that will give you access to the actual game world, where you will fight some enemies and die, which will lead you to the game over world, with your scores and statistics about how well you did. More about worlds will be explained later.

    Entities are exactly what they seem to be; they live in a world and do something in it: a button is an entity; your character is an entity; enemies and bullets are entities. They are the things that give life to the game.

    Given that, we will create the game world (there’s time to make the main menu world later, let’s jump to some action!) by extending FlashPunk’s World class:

    
    
    package
    {
    	import net.flashpunk.World;
    
    	public class GameWorld extends World
    	{
    
    		public function GameWorld()
    		{
    
    		}
    
    	}
    
    }
    

    Now that you have created a world, you need to tell FlashPunk that you want this world to be the active one. Let’s do it in Main.as:

    
    
    private var _gameWorld:GameWorld;
    
    public function Main():void
    {
    	super(550, 400, 30, false);
    
    	_gameWorld = new GameWorld();
    }
    
    override public function init():void
    {
    	trace("The game has started!");
    
    	FP.world = _gameWorld;
    }
    

    And don’t forget to import net.flashpunk.FP!


    Step 4: Adding an Entity, and Giving It an Image

    Now that we have our world, we can make an entity by extending the Entity class and adding it to our game world:

    
    
    package
    {
    	import net.flashpunk.Entity;
    
    	public class GameEntity extends Entity
    	{
    
    		public function GameEntity()
    		{
    
    		}
    
    	}
    
    }
    

    And in GameWorld.as:

    
    
    private var _gameEntity:GameEntity;
    
    public function GameWorld()
    {
    	_gameEntity = new GameEntity();
    
    	add(_gameEntity);
    }
    

    Notice that if you compile and run the game, the entity doesn’t appear in the screen. That’s because it has no image yet! Every entity can have a graphic object. This graphic can be a single image, a spritesheet with animations, tiled images — pretty much anything.

    We will add this little image to our entity:

    Our Entity

    An entity’s graphic can be accessed by the graphic property. That’s how we are going to put the image in it! First, embed it; then, just pass it to Image‘s constructor and FlashPunk will take care of transforming that into something visible for you. Compile and run now. Surprise! Our entity is there!

    
    
    package
    {
    	import net.flashpunk.Entity;
    	import net.flashpunk.graphics.Image;
    
    	public class GameEntity extends Entity
    	{
    		[Embed(source = "/../img/EntityImage.png")]
    		private const IMAGE:Class;
    
    		public function GameEntity()
    		{
    			graphic = new Image(IMAGE);
    		}
    
    	}
    
    }
    

    This is what you should get:

    The entity on the screen

    Step 5: Making the Entity Move

    Now that we have our entity on the screen, what about making it move? Each Entity has a function called update(), which you must override to use. This function is called by every world in the beginning of each frame. If you need to make your entity move, that’s the place where you put your code!

    
    
    override public function update():void
    {
    	x += 10 * FP.elapsed;
    	y += 5 * FP.elapsed;
    }
    

    And don’t forget to import:

    
    
    import net.flashpunk.FP;
    

    See it in action! (Refresh the page if you can’t see anything here.)

    You may have noticed the use of FP.elapsed. FP.elapsed gives the amount of time that elapsed since the last frame (in seconds), making it very easy to create time-based motion. However, for that to work, you must have set the fourth parameter to the Engine‘s constructor to false. Remember that (Step 2)? Setting it to false means that you want FlashPunk to run with a variable timestep, whereas setting it to true makes FlashPunk run on a fixed timestep. Doing the latter, you don’t need to use FP.elapsed. You will know that every time the update() function is called, a frame has passed.


    Step 6: Move the Entity as You Wish With Keyboard Input

    We’ve got the entity moving on just one direction in the last step. Introducing keyboard input: now you will be able to move the entity to where you want!

    FlashPunk has a class called Input which takes care of both keyboard and mouse input. In this tutorial, we will only use keyboard input for movement. It is very easy:

    
    
    override public function update():void
    {
    	if (Input.check(Key.A) || Input.check(Key.LEFT))
    	{
    		x -= 50 * FP.elapsed;
    	}
    	else if (Input.check(Key.D) || Input.check(Key.RIGHT))
    	{
    		x += 50 * FP.elapsed;
    	}
    
    	if (Input.check(Key.W) || Input.check(Key.UP))
    	{
    		y -= 50 * FP.elapsed;
    	}
    	else if (Input.check(Key.S) || Input.check(Key.DOWN))
    	{
    		y += 50 * FP.elapsed;
    	}
    }
    

    And the import statements:

    
    
    import net.flashpunk.utils.Input;
    import net.flashpunk.utils.Key;
    

    Input.check() returns true if the Key passed as an argument is being pressed at the time the function has been called. There are other very useful functions, like Input.pressed(), which returns true if the key has been pressed at the time the function has been called (i.e. the key was up a frame ago and is now down), or Input.released(), which does exactly the opposite.

    Another interesting thing that the Input class allows us to do is to define many keys under a single name. For example, we could define Key.UP, Key.W and Key.I as "UP", and only check for Input.check("UP"). That way, we can improve our function:

    
    
    public function GameEntity()
    {
    	graphic = new Image(IMAGE);
    
    	Input.define("UP", Key.W, Key.UP);
    	Input.define("DOWN", Key.S, Key.DOWN);
    	Input.define("LEFT", Key.A, Key.LEFT);
    	Input.define("RIGHT", Key.D, Key.RIGHT);
    }
    
    override public function update():void
    {
    	if (Input.check("LEFT"))
    	{
    		x -= 50 * FP.elapsed;
    	}
    	else if (Input.check("RIGHT"))
    	{
    		x += 50 * FP.elapsed;
    	}
    
    	if (Input.check("UP"))
    	{
    		y -= 50 * FP.elapsed;
    	}
    	else if (Input.check("DOWN"))
    	{
    		y += 50 * FP.elapsed;
    	}
    }
    

    And this is what you should get:


    Step 7: More About Entities

    Entities can do a lot more than just move around and have images. Let’s take a look at what surprises they can hold!

    Entities have a property called type. You can set this property to any string you want. This allows you to organize your entities into groups, which will prove very useful in the next step (about worlds). We can, for example, set our entity’s type to “GameEntity”:

    
    
    public function GameEntity()
    {
    	graphic = new Image(IMAGE);
    
    	Input.define("UP", Key.W, Key.UP);
    	Input.define("DOWN", Key.S, Key.DOWN);
    	Input.define("LEFT", Key.A, Key.LEFT);
    	Input.define("RIGHT", Key.D, Key.RIGHT);
    
    	type = "GameEntity";
    }
    

    Following on that, we have the useful world property and the added() and removed() functions. The world property allows you to access the world from within the entity’s code once the entity has been added to an world. It is like the stage property in common Flash development; the functions are like the ADDED_TO_STAGE and REMOVED_FROM_STAGE event listeners. Here’s an example of the functions working in GameEntity.as:

    
    
    override public function added():void
    {
    	trace("The entity has been added to the world!");
    
    	trace("Entities in the world: " + world.count);
    }
    
    override public function removed():void
    {
    	trace("The entity has been removed from the world!");
    }
    

    Step 8: Deeper Look at Worlds

    It is time to take a deeper look at worlds and how they work. First of all, FlashPunk can only have one world running at once, but your game can have as many worlds as you wish, as long as only one remains active every time.

    Worlds have update() functions just as entities do, but their function is a little different: there is actual code in the World class. That means you’ll have to call super.update() every time you override this function.

    Apart from entities, worlds can also have graphics added to them. Graphics are images that don’t need to be updated by you (FlashPunk still creates an entity to add them to the world, so the engine will still send a call to an update() function). You can add them by calling addGraphic().

    The most important thing about worlds is that they have several functions to retrieve certain entities: getType(), getClass(), getAll(), getLayer() and getInstance(). That way, you can have the world return an array of all the bullets currently in the game, so that you can perform a check against all of them for collision. Very handy, I must say!

    Take a look at the code added to World.as. We will use a second image as well:

    Our second entity
    
    
    [Embed(source = "/../img/EntityImage2.png")]
    private const IMAGE:Class;
    
    public function GameWorld()
    {
    	_gameEntity = new GameEntity();
    
    	add(_gameEntity);
    
    	addGraphic(new Image(IMAGE), 0, 50, 50);
    }
    
    override public function update():void
    {
    	super.update();
    
    	var entityArray:Array = [];
    
    	getType("GameEntity", entityArray);
    
    	for each (var entity:Entity in entityArray)
    	{
    		entity.x = entity.x > 550 ? 550 : entity.x;
    		entity.y = entity.y > 400 ? 400 : entity.y;
    	}
    }
    

    And don’t forget to import net.flashpunk.graphics.Image!

    In this code, the addGraphic() function call adds another graphic similar to _gameEntity‘s graphic – think of it as a NPC! – to the world in the position (50, 50). Lines 23-31 show an example of retrieving only entities of a particular kind: we call getType() to get only entities of the “GameEntity” type (currently only one entity). After that, we iterate through every entity retrieved and prevent them from getting past the right and bottom borders. (So, the entity can move outside the screen, but not far.) Simple, isn’t it?


    Step 9: Animations

    Time for something more interesting! FlashPunk supports animations of all kinds. All you have to do is, instead of creating an instance of Image, create an instance of Spritemap. This class receives a spritesheet and allows you to map frames and link to animations.

    In our entity’s class, embed this spritemap:

    Our Entity's Sheet

    Then, create an instance of Spritemap and pass the spritesheet as a parameter to the constructor. After that, it’s all about calling the add() and play() functions!

    
    
    [Embed(source = "/../img/EntitySheet.png")]
    private const SHEET:Class;
    
    private var _timeInterval:Number;
    
    public function GameEntity()
    {
    	graphic = new Spritemap(SHEET, 40, 20, onAnimationEnd);
    	Spritemap(graphic).add("Stopped", [0]);
    	Spritemap(graphic).add("Blinking", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 24);
    
    	Input.define("UP", Key.W, Key.UP);
    	Input.define("DOWN", Key.S, Key.DOWN);
    	Input.define("LEFT", Key.A, Key.LEFT);
    	Input.define("RIGHT", Key.D, Key.RIGHT);
    
    	type = "GameEntity";
    
    	Spritemap(graphic).play("Blinking");
    }
    
    private function onAnimationEnd():void
    {
    	Spritemap(graphic).play("Stopped");
    
    	_timeInterval = 0;
    }
    
    override public function update():void
    {
    	_timeInterval += FP.elapsed;
    
    	if (_timeInterval >= 3)
    	{
    		Spritemap(graphic).play("Blinking");
    	}
    
    	if (Input.check("LEFT"))
    	{
    		x -= 50 * FP.elapsed;
    	}
    	else if (Input.check("RIGHT"))
    	{
    		x += 50 * FP.elapsed;
    	}
    
    	if (Input.check("UP"))
    	{
    		y -= 50 * FP.elapsed;
    	}
    	else if (Input.check("DOWN"))
    	{
    		y += 50 * FP.elapsed;
    	}
    }
    

    The constructor of Spritemap (line 19) takes four arguments: a source to get a graphic from, the width and height of each frame of the spritesheet and a callback function to call when the animation ends (optional). In GameEntity‘s constructor, we create the Spritemap and define two animations: “Stopped”, which only contains the first frame and runs at 0 fps (stopped!) and “Blinking”, which contains all frames and runs at 24 frames per second.

    The rest of the code is there to play the “Blinking” animation every three seconds.

    Take a look at our entity blinking:


    Step 10: Collision

    With everything running well, it’s time to introduce another feature: collision detection. FlashPunk has a great collision detection system: all we need to do is set hitboxes for our entities and ask the world to check for collisions. For that, we will create another entity called Box which will contain the following graphic:

    Box image
    
    
    package
    {
    	import net.flashpunk.Entity;
    	import net.flashpunk.graphics.Image;
    
    	public class Box extends Entity
    	{
    		[Embed(source = "/../img/BoxImage.png")]
    		private const IMAGE:Class;
    
    		public function Box()
    		{
    			graphic = new Image(IMAGE);
    
    			setHitbox(60, 60);
    		}
    
    	}
    
    }
    

    And inside GameWorld.as:

    
    
    private var _box:Box;
    
    public function GameWorld()
    {
    	_gameEntity = new GameEntity();
    	_box = new Box();
    
    	add(_gameEntity);
    	add(_box);
    
    	_box.x = 200;
    	_box.y = 150;
    
    	addGraphic(new Image(IMAGE), 0, 50, 50);
    }
    

    The setHitbox() function sets a rectangle that will act as a hit box for the entity. The first two parameters are the width and height of the box. The next two parameters (optional) are the origin coordinates (x and y) of the rectangle. Doing the same for GameEntity:

    
    
    public function GameEntity()
    {
    	graphic = new Spritemap(SHEET, 40, 20, onAnimationEnd);
    	Spritemap(graphic).add("Stopped", [0]);
    	Spritemap(graphic).add("Blinking", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 24);
    
    	Input.define("UP", Key.W, Key.UP);
    	Input.define("DOWN", Key.S, Key.DOWN);
    	Input.define("LEFT", Key.A, Key.LEFT);
    	Input.define("RIGHT", Key.D, Key.RIGHT);
    
    	type = "GameEntity";
    
    	Spritemap(graphic).play("Blinking");
    
    	setHitbox(40, 20);
    }
    

    Now that we have both our entity and the box set up with hitboxes, we need to check for collisions in the world class:

    
    
    override public function update():void
    {
    	super.update();
    
    	var entityArray:Array = [];
    
    	getType("GameEntity", entityArray);
    
    	for each (var entity:Entity in entityArray)
    	{
    		entity.x = entity.x > 550 ? 550 : entity.x;
    		entity.y = entity.y > 400 ? 400 : entity.y;
    	}
    
    	if (_gameEntity.collideWith(_box, _gameEntity.x, _gameEntity.y))
    	{
    		trace("Collision!");
    	}
    }
    

    The collideWith() function checks collision with the entity passed as an argument, virtually placing the first entity (in this case, _gameEntity) in the position specified by the second and third arguments.

    Once a collision is detected, there must be a response to it. We will only change the position of the moving entity:

    
    
    override public function update():void
    {
    	super.update();
    
    	var entityArray:Array = [];
    
    	getType("GameEntity", entityArray);
    
    	for each (var entity:Entity in entityArray)
    	{
    		entity.x = entity.x > 550 ? 550 : entity.x;
    		entity.y = entity.y > 400 ? 400 : entity.y;
    	}
    
    	if (_gameEntity.collideWith(_box, _gameEntity.x, _gameEntity.y))
    	{
    		_gameEntity.x = _gameEntity.y = 0;
    	}
    }
    

    Take a look at the example. Try to move the entity into the box.


    Step 11: Creating a Simple Button – Adding an Image

    FlashPunk doesn’t have any buttons by default. Almost all games need buttons, so in this step we will create a Button class. First of all, a button has three states (as you may know from common Flash development): “Up”, “Over” and “Down”. This spritesheet illustrates that:

    A Button

    And now let’s start the class:

    
    
    package
    {
    	import net.flashpunk.Entity;
    	import net.flashpunk.graphics.Spritemap;
    
    	public class Button extends Entity
    	{
    		protected var _map:Spritemap;
    
    		public function Button(x:Number = 0, y:Number = 0)
    		{
    			super(x, y);
    		}
    
    		public function setSpritemap(asset:*, frameW:uint, frameH:uint):void
    		{
    			_map = new Spritemap(asset, frameW, frameH);
    
    			_map.add("Up", [0]);
    			_map.add("Over", [1]);
    			_map.add("Down", [2]);
    
    			graphic = _map;
    
    			setHitbox(frameW, frameH);
    		}
    
    		override public function render():void
    		{
    			super.render();
    		}
    
    	}
    
    }
    

    The setSpritemap() function sets a spritemap for the button and sets “animations” for the button. Always the image must have first the “Up” frame, then the “Over”, followed by the “Down” frame. There’s also a call to setHitbox(). The hitbox will be used to check whether the mouse is or isn’t over the button’s box.


    Step 12: Creating a Simple Button: Up/Over/Down Controls, Callback

    Now that we have our Button successfully showing an image, it’s time to create up, over and down controls. We will do it by creating two Boolean attributes: “over” and “clicked”. We will also detect whether the mouse is over the button’s hit box or not. Add these functions in Button.as:

    
    
    protected var _over:Boolean;
    protected var _clicked:Boolean;
    
    override public function update():void
    {
    	if (!world)
    	{
    		return;
    	}
    
    	_over = false;
    	_clicked = false;
    
    	if (collidePoint(x - world.camera.x, y - world.camera.y, Input.mouseX, Input.mouseY))
    	{
    		if (Input.mouseDown)
    		{
    			mouseDown();
    		}
    		else
    		{
    			mouseOver();
    		}
    	}
    }
    
    protected function mouseOver():void
    {
    	_over = true;
    }
    
    protected function mouseDown():void
    {
    	_clicked = true;
    }
    
    override public function render():void
    {
    	if (_clicked)
    	{
    		_map.play("Down");
    	}
    	else if (_over)
    	{
    		_map.play("Over");
    	}
    	else
    	{
    		_map.play("Up");
    	}
    
    	super.render();
    }
    

    And don’t forget to import net.flashpunk.utils.Input.

    Following the logic in update(): first of all, both attributes (_clicked and _over) are set to false. After that, we check if the mouse is over the button. If it isn’t, the attributes will remain false and the button will be in the “Up” state. If the mouse is over, we check whether the mouse button is currently down. If that’s true, the button is in the “Down” state and _clicked is set to true; if it’s false, then the button is in the “Over” state and the _over attribute is set to true. These attributes will define which frame the spritemap should go to.

    This button will be useless if you can’t detect when the user has effectively clicked it. Let’s change the class a bit in order to support callback functions:

    
    
    protected var _callback:Function;
    protected var _argument:*;
    
    public function Button(callback:Function, argument:*, x:Number = 0, y:Number = 0)
    {
    	super(x, y);
    
    	_callback = callback;
    	_argument = argument;
    }
    
    override public function update():void
    {
    	if (!world)
    	{
    		return;
    	}
    
    	_over = false;
    	_clicked = false;
    
    	if (collidePoint(x - world.camera.x, y - world.camera.y, Input.mouseX, Input.mouseY))
    	{
    		if (Input.mouseReleased)
    		{
    			clicked();
    		}
    		else if (Input.mouseDown)
    		{
    			mouseDown();
    		}
    		else
    		{
    			mouseOver();
    		}
    	}
    }
    
    protected function clicked():void
    {
    	if (!_argument)
    	{
    		_callback();
    	}
    	else
    	{
    		_callback(_argument);
    	}
    }
    

    Our button is done! This code will allow you to pass a callback function (and optionally an argument) to your button, so whenever the user clicks the button, the function will be called.


    Step 13: Creating a Simple Button: Adding It to the Screen

    Many steps and nothing on the screen… Time to put a button in there! It’s as simple as adding this code in GameWorld.as:

    
    
    [Embed(source = "/../img/ButtonSheet.png")]
    private const BUTTONSHEET:Class;
    
    private var _button:Button;
    
    public function GameWorld()
    {
    	_gameEntity = new GameEntity();
    	_box = new Box();
    	_button = new Button(onButtonClick, null);
    
    	_button.setSpritemap(BUTTONSHEET, 50, 40);
    
    	add(_gameEntity);
    	add(_box);
    	add(_button);
    
    	_box.x = 200;
    	_box.y = 150;
    
    	_button.x = 400;
    	_button.y = 200;
    
    	addGraphic(new Image(IMAGE), 0, 50, 50);
    }
    
    private function onButtonClick():void
    {
    	FP.screen.color = Math.random() * 0xFFFFFF;
    
    	trace("The button has been clicked!");
    }
    

    Now all you have to do is compile the project and the button will be there!


    Step 14: The Console

    And now the final feature from FlashPunk that will be presented in this tutorial! The Console is FlashPunk’s tool for debugging: it features logs, which are pretty much like traces; shows the time taken to run important engine step; and displays how many entities are on screen and the current FPS. It’s a great tool to use when developing your game. To enable it, just add the following line to Main.as:

    
    
    override public function init():void
    {
    	trace("The game has started!");
    
    	FP.console.enable();
    
    	FP.world = _gameWorld;
    }
    

    And to log anything in it, use the FP.log() function. For example, let’s change that trace() call:

    
    
    override public function init():void
    {
    	FP.console.enable();
    
    	FP.log("The game has started!");
    
    	FP.world = _gameWorld;
    }
    

    That’s pretty much it! You’ll see that the “Output” part from the debugging console now shows the log. You can go ahead and change all the trace() calls in our code to calls to FP.log().


    Conclusion

    And that’s our introduction to FlashPunk, covering the most important aspects of this amazing library: entities, worlds, images and animations; collision, buttons, input and movement. I hope you’ll like this library as much as I do – it really makes work easier!


  10. Rahul R Gaikwad says:
    September 27, 2011 at 8:27 am

    Today we’ll build a fully functional calendar widget using AS3. It’s not rocket science, just an excellent example of using the Date class, which can handle all the complexity of extracting times, dates, months and years. We are also going to use some Flash components, and make sure that this calendar is portable to Flash Builder, FlashDevelop, and so on.


    Final Result Preview

    Let’s take a look at the final result we will be working towards:


    Step 1: Brainstorming

    Before starting to build the code, let’s take a look at what we’ll need:

    • A class file, Calendar.as,
    • A cell grid, to place dates,
    • Labels for day names,
    • Function to get current date, month and year,
    • Function to get previous months’ days,
    • Function to get future months’ days,
    • Something to address the leap year issue,
    • Interface to pick any month and year,
    • Portability (for Flash Builder, FlashDevelop, and other IDEs).

    Step 2: Preparing the Calendar.as Class File

    In this step we shall create a basic structure of our Calendar.as class file.

    There are several ways of creating ActionScript class file, like using FDT, Flash Builder, FlashDevelop. And, of course, the “Higgs Boson” of this multimedia world: the one true Flash IDE. I am using Flash Professional. Create an ActionScript 3.0 class file. The following is the basic structure of Calendar.as to start with.

    
    
    package  {
    
    	import flash.display.Sprite;
    
    	public class Calendar extends Sprite {
    
    		//variables
    
    		public function Calendar () {
    
    			// constructor code
    		}
    	}
    }
    

    I am sure that you have saved this class file as Calendar.as in the new folder for this calendar app. If not please save it.

    Step by step we shall modify this Calendar.as to make it fully functional.

    In the next step we will create a few text fields to label the weekdays and dates.


    Step 3: Setting Up Text Formats for Dates and Weekdays

    In this step we will modify our class by declaring some variables and creating a new function setTextFormat( fontFace, fontSize ).

    We will also passing some parameters to the constructor of the class.

    Initially it will look like “Syntactic Sugar”, but as the tutorial progresses it will become “Syntactic Salt”. Sorry, but we want to keep this class compact so as to make it easily portable. The idea is to have only one class and that’s all.

    So, keep a close watch on the constructor’s number of parameters and their order as we progress.

    Back to modifying the document class…

    
    
    package  {
    
    	import flash.display.Sprite;
    	import flash.text.TextFormat;
    
    	public class Calendar extends Sprite {
    
    		//variables
    		private var dateCellFormat:TextFormat;
    		private var dayLabelTxtFmt:TextFormat;
    
    		public function Calendar( fontFace:String = "Arial", fontSize:int = 15 )
    		{
    			setTextFormat( fontFace, fontSize );
    		}
    
    		private function setTextFormat(whichFont:String, size:int):void	{
    
    			//date text format
    			dateCellFormat = new TextFormat();
    			dateCellFormat.font = whichFont;
    			dateCellFormat.color = 0xFFFFFF;
    			dateCellFormat.size = size;
    			dateCellFormat.align = "center";
    
    			//day label text format
    			dayLabelTxtFmt = new TextFormat();
    			dayLabelTxtFmt.font = "_sans";
    			dayLabelTxtFmt.color = 0x000000;
    			dayLabelTxtFmt.size = size - 3;
    		}
    	}
    }
    

    Observe all the parameters passed to the constructor: we have already assigned values to them. This is the way to create default values for parameters. If no parameters are specified when instantiating the class, these default values will be used instead. We will see this in coming steps.

    Nothing visible yet. Wait for a few steps.


    Step 4: Creating Cell Grid to Arrange Dates

    The calendar is made up of rows and columns forming a grid.

    But how many rows and columns?

    It depends on the calendar type – Vertical or Horizontal.

    Vertical view needs 7 (rows) x 6 (columns), while horizontal view needs 6 (rows) x 7 (columns) as shown:

    Horizontal and Vertical Calendars

    As our calendar is limited to horizontal view for this tutorial, we will need 7 columns and 6 rows. Thus total (7 x 6) = 42 cells.

    So, let us modify our class so that it will generate a grid required for calendar view. Along with adding an import statement, new variables and constructor parameters, we will also add a new function makeDatesCellGrid(..) to the class as shown:

    
    
    package  {
    
    	import flash.display.Sprite;
    	import flash.text.TextFormat;
    	import flash.text.TextField;
    
    	public class Calendar extends Sprite {
    
    		//variables
    		private var cellW:Number; //cell width
    		private var cellP:Number; //cell padding
    		private var allDatesCells:Array = new Array();
    		private var dateCellFormat:TextFormat;
    
    		private var dayLabelTxtFmt:TextFormat;
    
    		public function Calendar( fontFace:String = "Arial", fontSize:int = 15,
    					cellWidth:Number = 30, padding:Number = 3,
    					originX:Number = 15, originY:Number = 15 )
    		{
    			cellW = cellWidth;
    			cellP = padding;
    
    			setTextFormat( fontFace, fontSize );
    
    			makeDatesCellGrid( originX, originY );
    		}
    
    	   private function setTextFormat(whichFont:String, size:int):void {
    
    			//date text format
    			dateCellFormat = new TextFormat();
    			dateCellFormat.font = whichFont;
    			dateCellFormat.color = 0xFFFFFF;
    			dateCellFormat.size = size;
    			dateCellFormat.align = "center";
    
    			//day label text format
    			dayLabelTxtFmt = new TextFormat();
    			dayLabelTxtFmt.font = "_sans";
    			dayLabelTxtFmt.color = 0x000000;
    			dayLabelTxtFmt.size = size - 3;
    		}
    
    		private function makeDatesCellGrid(cellXPos:Number, cellYPos:Number):void {
    
    			//Create grid of date cells
    			for (var i:int = 0; i < 42; i++) {
    
    				var dateCell:TextField = new TextField();
    				addChild(dateCell);
    
    				//position cells to form a grid (7 x 6 = 42)
    				dateCell.x = cellXPos + (cellW * (i-(Math.floor(i/7)*7)));
    				dateCell.y = cellYPos + (cellW * Math.floor(i/7));
    
    				//put all date cells into array for further access
    				allDatesCells.push(dateCell);
    			}
    		}
    	}
    }
    

    Oops, lots of code is written and nothing visible yet. I know you are waiting to see some visible results. For that we will make a temporary change in makeDatesCellGrid by adding a new line as shown:

    
    
    private function makeDatesCellGrid(cellXPos:Number, cellYPos:Number):void
    {
    
    	//Create grid of date cells
    	for (var i:int = 0; i < 42; i++)
    	{
    
    		var dateCell:TextField = new TextField();
    		addChild(dateCell);
    
    		//position cells to form a grid (7 x 6 = 42)
    		dateCell.x = cellXPos + (cellW * (i-(Math.floor(i/7)*7)));
    		dateCell.y = cellYPos + (cellW * Math.floor(i/7));
    
    		//put all date cells into array for further access
    		allDatesCells.push(dateCell);
    
    		allDatesCells[i].text = i;
    	}
    }
    

    Wait…Wait. Now create a new Flash file for ActionScript 3.0 and save this file with any name (ideally Calendar.fla as I did) in the same folder where you saved Calendar.as. Now open the ActionScript panel by pressing “F9″ and type the following code:

    
    
    var myCalendar:Sprite = new Calendar();
    addChild(myCalendar);
    

    Now test the movie.

    DateCellGrid

    There are a few things to fix, like setting up the dates for current month, labels for days, etc.

    Also note that though the constructor can take parameters, we saw a result without passing any values for parameters. This is what I was talking about in the previous step.

    Observe the following two lines we placed inside the constructor,

    
    
    cellW = cellWidth;
    cellP = padding;
    

    We created these vars for global access. We have assigned values to these variables from constructor parameters.

    We used “cellW” for placing cells in grid form. We will use “cellP”, i.e. cell padding (the gap between neighbouring cells), in coming steps. So wait and watch.

    One more thing. After testing above code, remove the line allDatesCells[i].text = i; from the makeDatesCellGrid(..) function. We added it for testing purposes only. Actually, we are going to put dates in those text fields in coming steps.


    Step 5: Adding Names of Weekdays

    In this step we will add labels for weekdays to our calendar. For that we are going to add a new function makeDaysLabels(...) and call it inside the constructor.

    First of all, add new array weekDays[] at the start of the class under the //Variables declaration section. This array hold names of all weekdays as shown:

    
    
    private var weekDays:Array = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
    

    Now add the following function to the class.

    
    
    private function makeDaysLabels(cellXPos:Number, cellYPos:Number):void {
    
    	//Add week day names
    	for (var i:int = 0; i < 7; i++)	{
    
    		var dayLabel:TextField = new TextField();
    		addChild(dayLabel);
    
    		dayLabel.selectable = false;
    		dayLabel.text = weekDays[i];
    		dayLabel.setTextFormat(dayLabelTxtFmt);
    		dayLabel.x = cellXPos + (cellW * i);
    		dayLabel.y = cellYPos - 15;
    	}
    }
    

    Finally, call this function inside constructor as shown:

    
    
    public function Calendar( fontFace:String = "Arial", fontSize:int = 15,
    						cellWidth:Number = 30, padding:Number = 3,
    						originX:Number = 15, originY:Number = 15 )
    {
    	cellW = cellWidth;
    	cellP = padding;
    
    	setTextFormat( fontFace, fontSize );
    
    	makeDatesCellGrid( originX, originY );
    
    	makeDaysLabels( originX, originY );
    }
    

    Weekdays are ready and waiting for dates to have their right places.


    Step 6: Initializing and Decorating Dates’ Cells

    In this step we will make textfield background visible so that there’s no need to draw a rectangle shape. But if you want to add more style then after completing this tutorial go ahead and create rectangle instances as dates’ cells background and add a gradient color to them. For now it’s ok to set the textfield’s background to true and apply a solid color to it.

    Add the following new function to our class.

    
    
    private function monthSetup():void {
    
    	for (var i:int = 0; i < 42; i++){
    
    		allDatesCells[i].text = "";
    
    		//decor all cells
    		allDatesCells[i].background = true;
    		allDatesCells[i].backgroundColor = 0x000000;
    		allDatesCells[i].border = true;
    		allDatesCells[i].borderColor = 0xCCCCCC;
    		allDatesCells[i].selectable = false;
    		allDatesCells[i].width = allDatesCells[i].height = cellW - cellP;
    		allDatesCells[i].setTextFormat(dateCellFormat);
    	}
    }
    

    Then, call this function inside constructor as shown:

    
    
    public function Calendar( fontFace:String = "Arial", fontSize:int = 15,
    						cellWidth:Number = 30, padding:Number = 3,
    						originX:Number = 15, originY:Number = 15 )
    {
    	cellW = cellWidth;
    	cellP = padding;
    
    	setTextFormat( fontFace, fontSize );
    
    	makeDatesCellGrid( originX, originY );
    
    	makeDaysLabels( originX, originY );
    
     	monthSetup();
    }
    

    Test the movie.

    Dates' Cell background

    Cool… The cells are ready to hold dates for the selected month.


    Step 7: Arrange Dates for Selected Month

    We will add a new function arrangeDates(). This is the most important function for this Calendar app.

    We will be completing the following must-do tasks through this function:

    • Creating date object from Date class.
    • Identifying the column number for first day of selected month.
    • Getting maximum number of days for selected month (with respect to leap year, if applicable).
    • Putting dates at correct places for selected month.
    • Highlighting today’s date, if selected month is current month.

    Pretty challenging tasks, but interesting.

    Ok, back to the job. First we will declare some variables at the start of the class under the //Variables section as shown:

    
    
    private var currDateTime:Date = new Date();
    private var firstDay:Date = new Date(currDateTime.fullYear,currDateTime.month,1);
    private var firstDayColumn:uint = firstDay.day;
    private var daysOfMonths:Array = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
    private var maxDays:uint;
    

    Here currDateTime gives the current time, today’s date, and the current month and year.

    firstDay gives all info about the first day (i.e. Date 1) of the current month. Observe that we have passed the value for third parameter as “1″ for date. Try tracing with various dates to get an idea of what this is doing. But remember to make it “1″ again after testing.

    firstDayColumn, as the name suggests, gives the column number for the first day of current month,

    daysOfMonths array holds maximum number of days from “January…” to “…December”. But for “February” we have “28″ days; in case of leap year we must assign “29″ days as the maximum number of days for February. We will see it later in this step.

    maxDays will hold maximum number of days for current month.

    Fine. Good enough explanation for each var. It’s time for new function arrangeDates().

    In order to understand this function neatly, we will modify it gradually.

    So first, In this function we will get the column number for first day (i.e. Date 1) of a selected month as shown:

    
    
    private function arrangeDates():void {
    
    	//get column number for first day of the month
    	if (firstDay.day == 0)
    	{
    		//when last date of previous month is on saturday then move to second row
    		firstDayColumn = firstDay.day + 7;
    	}
    	else
    	{
    		firstDayColumn = firstDay.day;
    	}
    }
    

    This "firstDayColumn" is important since once we get column number for first day (i.e Date 1) then placing next dates becomes very easy. We will simply use this "firstDayColumn" number inside a for loop to place the next dates. We will see it soon in coming steps.


    Step 8: Getting the Maximum Number of Days for Selected Month

    We will modify the "arrangeDates()" function to get the maximum days for selected month as shown:

    
    
    private function arrangeDates():void {
    
    	//get column number for first day of the month
    	if (firstDay.day == 0)
    	{
    		//when last date of previous month is on saturday then move to second row
    		firstDayColumn = firstDay.day + 7;
    	}
    	else
    	{
    		firstDayColumn = firstDay.day;
    	}
    
    	//get max days for current month w.r.t leap year if any
    	maxDays = (firstDay.getFullYear()%4 == 0 && firstDay.getMonth() == 1 ? 29 : daysOfMonths[firstDay.getMonth()]);
    }
    

    The above new line is a shorthand method for an if statement. New users may consider it “Syntactic Salt”, but once used to it will consider it “Syntactic Sugar”.

    Observe the question mark “?” in the above line. On the left side of this question mark – i.e. "firstDay.getFullYear()%4 == 0 && firstDay.getMonth() == 1" – is a conditional statement. If this left side is true then the statement after the “?” mark (here 29) is executed; if it is false the statment on the right of the “:” mark (here daysOfMonths[firstDay.getMonth()]) is executed. See the image below for a better understanding.

    Short hand method for if statement

    Ok, back to our shorthand if statement. It gives the maximum number of days for selected month. But you have to consider leap years, too. In a leap year, February has 29 maximum days. This leap year comes every fourth year.

    So we have two conditions, one is to check if it is leap year and second is to check if it is February.

    To check whether current year is leap year we used modulus operator (which gives the remainder after dividing one number by another), as in "firstDay.getFullYear() % 4". If it gives a remainder of 0 (zero) then we can say that it is a leap year. For example, 2012 is a leap year, as (2012 % 4 == 0). Similarly (2016 % 4 == 0), so 2016 is a leap year, and so on. If the remainder is nonzero then obviously it is not a leap year. Thus we can detect leap years.

    (Editor’s note: actually, there’s a little more to it than that: years divisible by 100 are usually not leap years – unless they are also divisible by 400. To keep this tutorial simple, we’ll omit that, but you can program it in if you wish!)

    Now we will check whether the current month is “February”. Before that let us consider the index number for months generated by Date class. It starts from 0 for Jan, 1 for Feb, 2 for March and so on. So to find out whether the current month is “February”, we use "firstDay.getMonth() == 1". “1″ for “February”.

    If both these conditions are true then we set maxDays = 29; otherwise we refer to the "daysOfMonths" array.


    Step 9: Placing Dates of Selected Month at Their Positions

    Now we have "maxDays" and "firstDayColumn" with us so we are able to arrange dates for selected month.

    Modify "arrangeDates()" as shown below,

    
    
    private function arrangeDates():void {
    
    	//get column number for first day of the month
    	if (firstDay.day == 0)
    	{
    		//when last date of previous month is on saturday then move to second row
    		firstDayColumn = firstDay.day + 7;
    	}
    	else
    	{
    		firstDayColumn = firstDay.day;
    	}
    
    	//get max days for current month w.r.t leap year if any
    	maxDays = (firstDay.getFullYear()%4 == 0 && firstDay.getMonth() == 1 ? 29 : daysOfMonths[firstDay.getMonth()]);
    
    	//put dates for current month
    	for (var i:int = 0; i < maxDays; i++) {
    
    		allDatesCells[firstDayColumn + i].text = i + 1;
    		allDatesCells[firstDayColumn + i].setTextFormat(dateCellFormat);
    
    		allDatesCells[firstDayColumn + i].alpha = 1;
    	}
    }
    

    We set "allDatesCells[firstDayColumn + i].alpha = 1" for date field as we are going to set previous and next month’s date fields’ alpha to 0.5 in coming steps. So we set alpha = 1 in advance to avoid returning to this function, since this function is almost finished.

    Now "arrangeDates()" function has something to show. But we need to call it somewhere. The function "monthSetup()" is the right place to call this function.

    So modify function "monthSetup()" as shown:

    
    
    private function monthSetup():void {
    
    	for (var i:int = 0; i < 42; i++){
    
    		allDatesCells[i].text = "";
    
    		//decor all cells
    		allDatesCells[i].background = true;
    		allDatesCells[i].backgroundColor = 0x000000;
    		allDatesCells[i].border = true;
    		allDatesCells[i].borderColor = 0xCCCCCC;
    		allDatesCells[i].selectable = false;
    		allDatesCells[i].width = allDatesCells[i].height = cellW - cellP;
    		allDatesCells[i].setTextFormat(dateCellFormat);
    	}
    
    	arrangeDates();
    }
    

    At this point you can test the movie.

    Wow. exciting. See those dates at their positions.

    Dates at their positions

    Step 10: Highlighting Today’s Date

    In this step we will highllight today’s date. So modify the "for" loop in "arrangeDates()" as shown:

    
    
    private function arrangeDates():void {
    
    	//get column number for first day of the month
    	if (firstDay.day == 0)
    	{
    		//when last date of previous month is on saturday then move to second row
    		firstDayColumn = firstDay.day + 7;
    	}
    	else
    	{
    		firstDayColumn = firstDay.day;
    	}
    
    	//get max days for current month w.r.t leap year if any
    	maxDays = (firstDay.getFullYear()%4 == 0 && firstDay.getMonth() == 1 ? 29 : daysOfMonths[firstDay.getMonth()]);
    
    	//put dates for current month
    	for (var i:int = 0; i < maxDays; i++) {
    
    		allDatesCells[firstDayColumn + i].text = i + 1;
    		allDatesCells[firstDayColumn + i].setTextFormat(dateCellFormat);
    
    		allDatesCells[firstDayColumn + i].alpha = 1;
    
    		//Highlight today
    		if (firstDay.fullYear == currDateTime.fullYear && firstDay.month == currDateTime.month)
    		{
    			if(allDatesCells[firstDayColumn + i].text == currDateTime.date)
    			{
    				allDatesCells[firstDayColumn + i].backgroundColor = 0xEE5D15;
    			}
    		}
    	}
    }
    

    Test movie to see today’s date highlighted.

    We are very close to getting that “Calendar” feel. Once the dates of previous month and next month are placed, then we are done – for the current month, at least.


    Step 11: Adding Dates of the Previous Month

    We want to add dates from before the “firstDayColumn”, so we will get all previous date fields in reverse order by using a decrementing "for" loop.

    Add the following new function to the class:

    
    
    private function prevMonthDates():void {
    
    	var prevMonthFirstDay:Date = new Date(firstDay.fullYear,firstDay.month,firstDay.date - 1);
    
    	for (var i:int = firstDayColumn-1; i >= 0; i--) {
    
    		allDatesCells[i].text = prevMonthFirstDay.date - ((firstDayColumn - 1) - i);
    		allDatesCells[i].setTextFormat(dateCellFormat);
    		allDatesCells[i].alpha = 0.5;
    	}
    }
    

    Now call this function inside "monthSetup()" as shown:

    
    
    private function monthSetup():void {
    
    	for (var i:int = 0; i < 42; i++){
    
    		allDatesCells[i].text = "";
    
    		//decor all cells
    		allDatesCells[i].background = true;
    		allDatesCells[i].backgroundColor = 0x000000;
    		allDatesCells[i].border = true;
    		allDatesCells[i].borderColor = 0xCCCCCC;
    		allDatesCells[i].selectable = false;
    		allDatesCells[i].width = allDatesCells[i].height = cellW - cellP;
    		allDatesCells[i].setTextFormat(dateCellFormat);
    	}
    
    	arrangeDates();
    	prevMonthDates();
    }
    

    Test the movie to see the previous month’s dates placed at their positions.


    Step 12: Adding Dates of the Next Month

    In this step we will add dates of next month. Add the following new function to the class as shown:

    
    
    private function nextMonthDates():void {
    
    	for (var i:int = 1; i < (42 - maxDays - (firstDayColumn - 1)); i++){
    
    		allDatesCells[(firstDayColumn - 1) + i + maxDays].text = i;
    		allDatesCells[(firstDayColumn - 1) + i + maxDays].setTextFormat(dateCellFormat);
    		allDatesCells[(firstDayColumn - 1) + i + maxDays].alpha = 0.5;
    	}
    }
    

    Now call this function inside "monthSetup()" function as shown:

    
    
    private function monthSetup():void {
    
    	for (var i:int = 0; i < 42; i++){
    
    		allDatesCells[i].text = "";
    
    		//decor all cells
    		allDatesCells[i].background = true;
    		allDatesCells[i].backgroundColor = 0x000000;
    		allDatesCells[i].border = true;
    		allDatesCells[i].borderColor = 0xCCCCCC;
    		allDatesCells[i].selectable = false;
    		allDatesCells[i].width = allDatesCells[i].height = cellW - cellP;
    		allDatesCells[i].setTextFormat(dateCellFormat);
    	}
    
    	arrangeDates();
    	prevMonthDates();
    	nextMonthDates();
    }
    

    Test the movie to see dates of next month placed at their positions.

    At this point our calendar is ready, displaying all the dates required in the current month’s display. Now in the coming steps we will allow the user to select any month and any year, to complete the Calendar application.


    Step 13: Adding the Capability to Select Any Month

    Selecting any month will add more sense to our Calendar. To select any month from the list, the "ComboBox" component is the best option available.

    Therefore we need to add a ComboBox which holds a list of months. It should be placed at an appropriate position, somewhere near the calendar. So we will allow placing this ComboBox as per the developer’s choice. How will we allow the developer to change this? We will pass parameter for the X and Y positions of this ComboBox to the constructor of Calendar.as.

    To add and place the ComboBox, first consider the following tasks we must perform:

    • Passing parameters for the ComboBox’s "X" and "Y" positions to the constructor.
    • Adding new function "monthPicker(...)" where we will manipulate the ComboBox.
    • Adding one more new function "pickMonth()" which will hear the ComboBox’s events and will call a function to show the selected month.
    • Importing the ComboBox component by dragging it from the Component Panel to the Library Panel of our FLA.

    First, add the following import statements to the class,

    
    
    import flash.events.Event;
    import fl.controls.ComboBox;
    import fl.data.DataProvider;
    

    Then add new variables at start of the class under //Variables section as shown:

    
    
    private var months:Array = [
    								{label:"January", data:0},
    								{label:"February", data:1},
    								{label:"March", data:2},
    								{label:"April", data:3},
    								{label:"May", data:4},
    								{label:"June", data:5},
    								{label:"July", data:6},
    								{label:"August", data:7},
    								{label:"September", data:8},
    								{label:"October", data:9},
    								{label:"November", data:10},
    								{label:"December", data:11},
    							];
    
    private var monthPickerCB:ComboBox; //combobox to pick a month
    

    We will use the "months" array to put values inside combobox.

    Ok, now let us modify the constructor function as shown:

    
    
    public function Calendar( fontFace:String = "Arial", fontSize:int = 15,
    							cellWidth:Number = 30, padding:Number = 3,
    							originX:Number = 15, originY:Number = 15,
    							cbX:Number = 15, cbY:Number = 15 )
    {
    
    		cellW = cellWidth;
    		cellP = padding;
    
    		monthPickerCB = new ComboBox();
    
    		setTextFormat( fontFace, fontSize );
    
    		makeDatesCellGrid( originX, originY );
    
    		makeDaysLabels( originX, originY );
    
    		monthSetup();
    
    		monthPicker( cbX, cbY );
    }
    

    We added the parameters "cbX" and "cbY" into the constructor’s signature to pass position values specified by user, or to use default values if not specified.

    Then we created a ComboBox instance as "monthPickerCB = new ComboBox()".

    We called "monthPicker(...)" in advance, as we are going to create it now.

    So we will add two new functions "monthPicker(...)" and "pickMonth(...)" as shown:

    
    
    private function monthPicker(cbX:Number, cbY:Number):void {
    
    	monthPickerCB.dataProvider = new DataProvider(months);
    	addChild(monthPickerCB);
    
    	//position combobox
    	monthPickerCB.x = cbX;
    	monthPickerCB.y = (cellW * 6) + cbY;
    
    	monthPickerCB.selectedIndex = currDateTime.month;
    
    	monthPickerCB.addEventListener(Event.CHANGE, pickMonth);
    }
    
    private function pickMonth(e:Event):void {
    
    	firstDay.month = ComboBox(e.target).selectedItem.data;
    	monthSetup();
    }
    

    One more step and we are done adding the ComboBox.

    Drag the ComboBox from the Component panel into your Flash file’s Library panel. (Use the Window menu if you can’t find the panels.) This way, we can access the ComboBox component and its classes at runtime.

    Combobox and its prerequisites in the library.

    Test the movie to see combobox at bottom left of the calendar (as default value).

    Now you can display all the months, for the current year.

    Exciting… So we will now add year selection, giving one more dimension to our calendar.


    Step 14: Adding the Capability to Select Any Year

    Selecting any year will add one more dimension to our Calendar. To select any year within a range, the NumericStepper component is a good choice.

    Therefore we will add "NumericStepper" component which will allow the user to increment or decrement the selected year. As with the ComboBox, we will pass parameters to the constructor to specify its X and Y positions.

    To add and place a NumericStepper, we’ll have to perform the following tasks:

    • Passing parameters for NumericStepper’s "X" and "Y" positions to the constructor.
    • Adding new function "yearPicker(...)" where we will manipulate NumericStepper.
    • Adding one more new function "pickYear()" which will hear NumericStepper events and will tell to show the selected year.
    • Importing the NumericStepper component by dragging it from the Component panel to the Library panel of our FLA.

    First, add the following import statement to the class,

    
    
    import fl.controls.NumericStepper;
    

    Then add a new variable at the start of the class under the //Variables section as shown:

    
    
    private var yearPickerNS:NumericStepper; //numeric stepper to pick a year
    

    Ok, now let us modify constructor function as shown:

    
    
    public function Calendar( fontFace:String = "Arial", fontSize:int = 15,
    							cellWidth:Number = 30, padding:Number = 3,
    							originX:Number = 15, originY:Number = 15,
    							cbX:Number = 15, cbY:Number = 15,
    							nsX:Number = 26, nsY:Number = 15,
    							monthsRange:int = 39 )
    {
    
    	cellW = cellWidth;
    	cellP = padding;
    
    	monthPickerCB = new ComboBox();
    
    	yearPickerNS = new NumericStepper();
    
    	setTextFormat( fontFace, fontSize );
    
    	makeDatesCellGrid( originX, originY );
    
    	makeDaysLabels( originX, originY );
    
    	monthSetup();
    
    	monthPicker( cbX, cbY );
    
    	yearPicker( nsX, nsY, monthsRange );
    }
    

    We have added three parameters: "nsX", "nsY" and "monthsRange". The first two are to specify the position, and the third one is to specify the range (previous and next months). 39 will allow to pick any year within the next and previous 40.

    OK, now we will add two new functions "yearPicker(...)" and "pickYear(...)", as shown:

    
    
    private function yearPicker(nsX:Number, nsY:Number, maxYrsRange:int):void {
    
    	yearPickerNS.maximum = currDateTime.fullYear + maxYrsRange;
    	yearPickerNS.minimum = currDateTime.fullYear - maxYrsRange;
    	yearPickerNS.value = currDateTime.fullYear;
    	addChild(yearPickerNS);
    
    	//position numeric stepper
    	yearPickerNS.x = monthPickerCB.width + nsX;
    	yearPickerNS.y = (cellW * 6) + nsY;
    
    	yearPickerNS.addEventListener(Event.CHANGE, pickYear);
    }
    
    private function pickYear(e:Event):void {
    
    	firstDay.fullYear = e.target.value;
    	monthSetup();
    }
    

    One more step and we are done adding the numeric stepper.

    Drag the Numeric Stepper component from the Component panel to your Flash file’s Library panel. This way, we can access the Numeric Stepper component and its classes at runtime.

    That’s it. Test your movie to see a basic Calendar App running.

    Step 15: Customizing the Calendar

    We were testing the Calendar app with default values. Now we will customize it by passing different parameter values to its constructor.

    To start with, we will try using the different fonts available on our system.

    So, in the Flash file, go to the first statement in the ActionScript panel as shown:

    
    
    var myCalendar:Sprite = new Calendar();
    addChild(myCalendar);
    

    Click inside parenthesis next to new Calendar, and type "Courier New". Now your statement will look like this:

    
    
    var myCalendar:Sprite = new Calendar("Courier New");
    

    Test the movie to see the new font applied to dates.

    Now try changing next parameter (font size) like so:

    
    
    var myCalendar:Sprite = new Calendar("Courier New", 17);
    

    While typing the next parameter you will see a code hint pop up, showing all necessary parameters with their default values, like so:

    Code hint for constructor parameter

    Make sure all parameters are there in the code hint popup. There is a bug(?) I have found when I was working on one project, which I’d like to make you aware of.

    When I was writing a document class, at a point when there were only four parameters in the constructor signature, I closed this class file. When I got back to the work, I continued working on this class. At one point there were six parameters. Then I wanted to check this parameter passing stuff. So I opened the Flash file I created for this project and started typing parameters, as we did in our Calendar Flash file. I was expecting my newly added parameters to be displayed in code hints… but surprisingly there were still only four parameters.

    I saved and restarted all related files but the result was the same. After lots of testing I found the reason. The reason was, I created a new folder in the same folder where the document class was placed. I removed this folder outside the main folder, then I opened the class file to make some changes and I saved it. Then I went back to Flash file and started typing parameters and this time all parameters showed up.

    Ok, not a severe bug, but the lesson is: be careful while setting up a folder structure for your project.

    So back to the point where we left off. Try passing proper values for different parameters. You can also set up variables in Flash file (or in a class), so if one value is changed then other related parameters will also get adjusted accordingly – for example, if you want to increase the Font Size then Cell Width must increase accordingly, and so on.


    Step 16: Checking the Portability of This Calendar App

    The real power of this class is that you can use it in any of your project like so:

    • Using in Flash IDE (as we’ve been doing)
    • Calling this Calendar.as inside another document class.
    • Using it with FlashDevelop.
    • Using it with Flash Builder.

    We have already seen how to instantiate Calendar.as in Flash timeline code through this tutorial.

    Now we will see how to call it in another class.

    There is nothing much that we have to do differently when calling our class from another one. We simply put the same code we typed in Flash timeline into some other class. See the "Main.as" class below for better understanding:

    
    
    package
    {
    	import flash.display.Sprite;
    
    	public class Main extends Sprite
    	{
    		public function Main():void
    		{
    			init();
    		}
    
    		private function init():void
    		{
    			var c:Sprite = new Calendar();
    			addChild(c);
    		}
    	}
    }
    

    You can use the above “Main.as” in Flash, FlashDevelop, FlashBuilder, FDT. Only you will have to carry Calendar.as, “Main.as” in your project folders.

    In Flash IDE set this “Main.as” as Document class using Property Inspector panel. Make sure you have both Calendar.as, “Main.as” in your project folder. Also make sure you have “Combobox” and “NumericStepper” in your library panel. Now you can test the movie to see the working calendar.

    FlashDevelop

    Now we will test it with FlashDevelop 4.

    Create a new folder “Calendar_FD”.

    Open FlashDevelop, create a new project, and browse for the above "Calendar_FD" folder. Press OK to create new project.

    FlashDevelop Select Project window

    Inside “Calendar_FD” folder, you will see three new folders: “bin”, “lib” and “src”.

    Now in the “src” folder copy Calendar.as. Also copy above “Main.as” we created and replace it with the auto generated “Main.as” in the same folder.

    Now every thing is set up. But what about the "ComboBox" and "NumericStepper" components? Here no Library panel is present, unlike in the Flash IDE.

    The solution to this issue is making SWC files. We will create a "CalendarComp.swc" file.

    Create a new FLA (in Flash Pro), name it “CalendarComp.fla”, and save it anywhere (but remember its path).

    Drag "ComboBox" and "NumericStepper" components to the Library panel and save the file.

    Open Publish Settings and in the “Flash” tab check “Export SWC” under “SWF settings” group. Hit Publish.

    PublishSettings_SWC

    "CalendarComp.swc" is created in the folder where you saved "CalendarComp.fla", so browse to this folder and copy "CalendarComp.swc" to the "lib" folder of the "Calendar_FD" main folder.

    Back in FlashDevelop, look in the Project Panel. Right click "CalendarComp.swc" and select "Add to Library". Now we can access all class files required for our components, just like in the Flash IDE.

    Add CalendarComp.swc to library.

    Finally click “Test Project” to see your Calendar app running.

    Flash Builder

    How about Flash Builder 4?

    Create a new folder, “Calendar_FB”.

    Open Flash Builder and create a new project.

    Flash Builder Select Project Menu.

    Browse for the above “Calendar_FB” folder. Also enter a project name (I used “MyProject” as a project name). Press Finish to create a new project.

    Flash Builder Select Project window.

    Inside the “Calendar_FB” folder, you will see a “src” directoy, which already contains “MyProject.as” as the main class.

    MyProject Folder structure.

    Copy our Calendar.as class file to this folder. It is now visible in the “Package Explorer”.

    MyProject Folder structure.

    As in, FlashDevelop there is no library panel like the Flash IDE has. So how to get "ComboBox" and "NumericStepper" components?

    The solution is to use a SWC, like we did with FlashDevelop. But you need to specify the class path in Flash Builder.

    So first copy the "CalendarComp.swc" we created in the above section for FlashDevelop, and paste this file inside the “src” folder of the “Calendar_FB” main folder.

    In Flash Builder we need to add a class path. So click on Project > Properties to open the “Properties” window. Select “ActionScript Build Path” and click the “Add SWC…” button. Then browse for “CalendarComp.swc” which you pasted in the “src” folder.

    Project properties.

    Modify “MyProject.as” as shown:

    
    
    package
    {
    	import flash.display.Sprite;
    
    	public class MyProject extends Sprite
    	{
    		public function MyProject():void
    		{
    			var myCalendar:Sprite = new Calendar();
    			addChild(myCalendar);
    		}
    	}
    }
    

    Finally click “Run My Project” to see your Calendar app running.


    Conclusion

    So, friends, I would like to stop at this stage. I hope you have got something useful from this tutorial that will help in your coming projects. Best of luck… See you soon.

    In this tutorial we saw the logical use of the "Date()" class in AS3. We addressed the leap year issue. We displayed the next and previous month’s dates. We saw how to deal with Flash components. We also checked the portability of this Calendar app using FlashDevelop, Flash Builder and Flash Pro. During the process we also saw how to create and use SWC files to access Flash components outside Flash Pro.

    All good. Friends, keep reading Activetuts+. Enjoy!


Leave a Reply

Click here to cancel reply.

search search search search search
Find an Article
Categories
  • Flash Video Training
  • Hints and Tips
  • Recommended
Please Support Our Sponsors
Recent Posts
  • Workshop Coding Challenge: Fix This Breakout Game
  • Enable the Latest AIR SDK in Flash Professional CS5.5+
  • Quick Tip: Versioning Your Files With Dropbox (via Webdesigntuts+)
  • Workshop: Nuclear Outrun – Critique
  • Understanding Variables, Arrays, Loops, and Null: The Post-it Note Analogy
Tag Cloud
2011 ActionScript Active Activetuts+ Adobe animation Basic Basix Best Build Button Character Create Creating Critique Custom design Effect Effects Files Flash from Game Guide HTML5 Introduction Macromedia Motion Muzzle part Player Premium Professional Quick Silverlight Simple Text Tool Tutorial Tuts+ Tween Using Video website Workshop
About Our Site:

Hey there and welcome to "Flash Video Training Source", a resource for anybody interested in learning more about Adobe's great tool. We feature educational videos, which will help you master Adobe Flash and help you get to know all of its features. We at "Flash Video Training Source" believe that video training and video... more

Why don't you follow us on Twitter and get the latest video tutorials twitted to your account. Just click on the floating twitter bar to your right!

Go Back In Time
May 2012
M T W T F S S
« Apr    
 123456
78910111213
14151617181920
21222324252627
28293031  
Pretty Blank Box
top

Blogroll

  • Development Blog
  • Documentation
  • Plugins
  • Suggest Ideas
  • Support Forum
  • Themes
  • WordPress Planet

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Archives

  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
Powered by WordPress  |  Designed by Elegant Themes  |  Lightning Fast Hosting by Site 5 Hosting