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 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 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:

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

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"), "_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.

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:
- When the game has ended:
GAME_ENDED
. - When the score has changed:
SCORE_CHANGE
. - When the Tweets that we load are ready to use:
TWEETS_READY
. - 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

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"; 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"; 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:

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.

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.


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:

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.

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.
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Update me weeklyEnvato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Translate this post