Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  1. Code
  2. Games

Golden Eggs: Build a Flash Game Using Twitter API Calls

Read Time:31 minsLanguages:

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 readyStep 1: Let's get the assets readyStep 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.






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 menuStep 3: Arrange the menuStep 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 TweenLiteStep 4: Prepare TweenLiteStep 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.

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:

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

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.

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

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 gameStep 7: Cleaning up the stage for a new gameStep 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:

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:

Now the function that will make things come back:

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

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.

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

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

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:

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

And we will fade it out in our endGame function:

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:

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:

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 gameStep 11: Starting our gameStep 11: Starting our game

Then we will need to work in our class:

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.

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:

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 errorsStep 12: Handling errorsStep 12: Handling errors

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.

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 gameStep 13: Initializing our gameStep 13: Initializing our game
Step 13: Initializing our gameStep 13: Initializing our gameStep 13: Initializing our game

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).

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:

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:

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

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 scoreStep 18: Showing scoreStep 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.

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:

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.

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.

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.

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:

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 objectsStep 22: Creating Tweet objectsStep 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:

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


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.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.