Creating an AIR Game

Creating an AIR Game


Author:
Craig Harrell
Date: 11/27/2008
Contents:
  • Setting up an AIR App
  • Applying components
  • Creating XML Document
  • Getting the XML
  • Adding Actionscript
  • Deploying the app
Introduction:

We all want to create cool applications. Maybe you already have one in mind, but don't know how to get from start to finish. This tutorial introduces you to the AIR API and how to use it to create a simple game of chance using Flex components and a little actionscript. Below is the final product before compiling it into an AIR app. Use Flex Builder 3 to import this application so you can review it and make changes as you see fit. View Flex Builder 3 Help Docs to find out how to import an application. You can also download the final AIR application to play with. Make sure you have downloaded and installed the AIR Player from Adobe first.

Application Download

Flex File Download

 

Setting up your AIR Application

If your using this application or writing your own you will probably want to look at and change the [applicationName]-app.xml file. This file contains some basic settings and not so basic settings to enable or disable different application options. This file is automatically created when you create an AIR application in Flex Builder 3. For this application we want to set some basic attributes within this file. Open it and lets take a look at this file.

45 <systemChrome>none</systemChrome>

48 <transparent>true</transparent>

57 <maximizable>true</maximizable>

 

Line 45 deals with the window around our application. In every application your operating system places a window around the guts of the application visible components. We don't want to show this, because we want to make it look like the 8 ball is floating freely.

Line 48 turns the background of the application to visible or transparent. Again we want to make our application seem to float freely on our screen so we don't want a background messing this effect up, so we set the transpancy to true.

Line 57. If you're starting from scratch then this line is commented out. We want to maximize this application upon start so that our 8 ball doesn't disappear from our screen when dragged.

That is it for editing the file. We could set some more different attributes, but we are going to keep this simple and leave it at that.

 
Applying Components

Next let us add our components. I created a eight ball image in my favorite image creator, you can use this or create your own. If you create your own you want to make sure it is large enough to hold all the items within it. I used a size of 360 by 380 for mine. Add an image component to the stage and use the style editor to set the horizontal center and vertical center to zero or absolute center. Then set the source to the image you choose to use.

Next add a canvas component to the stage and use the style editor to the absolute center as well. Then select the corner radius and set it to 100 to turn it into a circle. Set the width of the canvas to 190 and the height to 184. Change the background color to black. This should give you a nice black circle centered on the 8 ball image.

Next move the label component to the stage and again use the style editor to move it to the absolute center. Change the text color to white and set it to bold. Then give it the id of "answers_txt".

I decided to add some instructions to my app by moving another label component to the stage and setting the horizontal center to zero and the vertical center to 109. Then added the following to the text attribute: "Ask me a question then shake me for the answer." Again I changed the text color to white so it would easily be read against the black of the 8 ball. So your component code should look something like this:

<mx:Image source="assets/images/8ball.png" width="360" height="380" horizontalCenter="0" verticalCenter="0"/>
<mx:Canvas width="190" height="184" horizontalCenter="0" verticalCenter="0" borderStyle="solid" cornerRadius="100" backgroundColor="#000000" borderColor="#000000">
<mx:Label horizontalCenter="0" verticalCenter="0" id="answers_txt" color="#FFFFFF" fontWeight="bold" fontSize="14"/>
</mx:Canvas>
<mx:Label text="Ask me a question then shake me for the answer" color="#FFFFFF" horizontalCenter="0" verticalCenter="109"/>

 

Creating the XML Document

Before we get into creating the xml document that will contain our answers, let us first look at the folder structure I have created for this application. The reason for this is as your applications grow in size and complexity you will want a "framework" to keep your applications organized and easy to maintain. I have adopted this as a pretty good way of keeping things organized and by no means suggest that it is the best or last say in how to organize your applications, but that it works well for me.

I've created a folder off of the Flex created folder "src" called "assets". Since this application has data and images I've created two subfolders under assets called "images" and "data". If I had custom components I would have a subfolder called "components" and within it have more folders categorizing what those custom components were. Such as displays and what have you. I'm sure you get the picture so lets move on to the xml document.

Create your folder structure as you see fit and create a file called "8ballAnswers.xml". Place the following code in it.

<answers>

<answer>
Yes
</answer>

<answer>
No
</answer>

<answer>
Maybe
</answer>

<answer>
We'll See
</answer>

<answer>
Are you kidding
</answer>

<answer>
Be patient
</answer>

<answer>
Ask me tomorrow
</answer>

</answers>

I choose to set up my xml as simple as possible and since this is a list of answers used the word answers as my main body tag and answer to set apart my answers. This is it. You can add more answers as you see fit, just keep the same basic structure and make sure you count how many you have so you can edit some actionscript code later to ensure the random answer. This will become clear momentarily.

 
Getting the XML

Next we need to retrieve the xml document we just created. This is done using a Flex component called "HttpService". We use the HttpService component because we want to have our information returned as XML and this is the easiest way of doing so. Add the following script to your app.

<mx:HTTPService url="assets/data/8ballAnswers.xml" resultFormat="e4x" id="answers" fault="Alert.show(event.toString())">
</mx:HTTPService>

Next we want to turn our result data into a list/ Array to easily pull our answers out of it. So we use the Flex component called, "XMLListCollection". This neatly places our xml into a list/array structure without alot of extra coding.

<mx:XMLListCollection id="xmlList" source="{answers.lastResult.answer}" />

That is it we now have our data and it is formatted the way we need it. Let's move on to the fun part.

 
Adding Actionscript

Now we need to add the actionscript to get this all working as it should. First though let's edit the application tag a little and add a few things that will help our application appear how we want it and trigger the events we need to have trigger. He is what your application tag should look like.

<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="423" height="408"
showFlexChrome="false" title="My Magic 8 Ball" xmlns:ns1="assets.components.*"
initialize="init()" mouseUp="stopDragging(event)" mouseDown="dragThis(event)">

We need to remove the flex chrome which is like a window chrome first otherwise our 8 ball won't appear to float. Next we need to initialize the application so that the data we need can be called and gathered and the application sizes to fill the screen. We do this through an actionscript function called init(). Next we need to add mouse events that will trigger when the user mouses down on the application to shake it and lets up on the mouse to get the answer. Now let us move on to the actionscript that will make these events possible.

import mx.core.Application;
import mx.events.DragEvent;
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;

//initialize application by maximizing it and retrieving the xml data.
private function init():void
{
//maximize the app so that the 8 ball doesn't disappear
Application.application.maximize();
//collect answers from xml document
answers.send();
}

 

First thing in our actionscript is to import the classes we will need to use to have everything work properly. We import the Application, DragEvent, ResultEvent, and Alert classes. Our first function initializes our application to gather the xml data through the use of the httpservice tag and resizes the application itself to the full size of the screen.

//initialized on mouse down
private function dragThis(evt:MouseEvent):void
{
//start drag to resemble shaking ball when mouse button is pressed and held
this.startDrag();
}
//called when mouse is up
private function stopDragging(evt:MouseEvent):void
{
//stop drag of ball when mouse button is released
this.stopDrag();
getAnswer();
}

Next we create two more functions to handle our dragging of our app. The "this" statement pertains to the root application. So when you see "this.startDrag" it is saying start dragging the root application. The statement "this" refers to the current root so if you add on to the application with custom components and what have you the statement "this" will relate to where you have your actionscript. Did I confuse you yet?

Our stopDragging function is when we actually take the information gathered from the xml doc and put it to use. We create a custom function that handles this called "getAnswers()". This allows us to apply actionscript to randomly generate an answer every time the ball is shaken.

//collect answer and randomly select the one to show.
private function getAnswer():void
{
// 7 answers but since we start counting at zero we put 6
var randomNumber:int = (Math.floor(Math.random() * 6));
//apply random number to the array of the xml collection to pull an answer
answers_txt.text = xmlList.toArray()[randomNumber].toString();
}

Actionscript counts from zero. Remember this it's important if you don't want to end up banging your head off your keyboard. So where we would start from one actionscript starts from zero. SO if we have 7 answers actionscript counts it as 0,1,2,3,4,5,6 six answers. To generate a random response we need to do some math. Actionscript has a built in Math class that helps us do this, although be it not always easy. Math.floor is rounding the number down that it is given to the next whole number. Math.random only returns a value between 0 and 1. So it could return .25. We need to times this by the number of answers we have so thus where the *6 comes into play to get a number between 0 and 6. Next we use the number generated to find the answer in the array and feed it to our label so the user can see it. And we are done with the actionscript. Pretty simple huh?

 
Deploying the application

Next we want to just run a quick test of the application so if your using Flex hit the run button. Shake the 8 ball and get an answer to that burning question. Hopefully it's what you expected. Now close it up and go back to Flex. Right click on the 8 ball application folder in the tree menu to your left. ( Where you have your list of all your flex applications). Select Export from the menu that appears. A new window appears then select "Release Build". Click next. You can now set some different attributes here like allowing source view. I would leave the defaults alone until you get more comfortable with how things work. At the bottom of this window you can direct Flex where to create your install file for the application the default is within the application folder itself. Go ahead and click next when you have things set up as you would like.

Depending on whether or not you feel like purchasing a certificate or not you have the option to create one that is not signed. This is nice for just messing around. If you are seriously going to start building and deploying applications on a large scale it would be worth investing in a digitally signed certificate. Anyway if you don't already have one create one then browse to it. Once you have your certificate and password entered click next.

It will then ask you what files and folders you want to include in the the final application. Just go with the default settings. This will prevent you from accidentally not including something you should have. Then click finish. Once that is clicked it will create your new AIR app and it will be ready for distribution.

 

 
 
All ColdFusion Tutorials By Author: Craig
  • Fusebox 4.1 For Beginners Part 1
    This four part series will introduce cf beginners to the fusebox frame work and help them get a grasp of this powerful technology.
    Author: Craig
    Views: 41,586
    Posted Date: Monday, July 4, 2005
  • Fusebox 4.1 For Beginners Part 2
    This four part series will introduce cf beginners to the fusebox frame work and help them get a grasp of this powerful technology.
    Author: Craig
    Views: 51,593
    Posted Date: Monday, July 4, 2005
  • Fusebox 4.1 For Beginners Part 3
    This four part series will introduce cf beginners to the fusebox frame work and help them get a grasp of this powerful technology.
    Author: Craig
    Views: 35,486
    Posted Date: Monday, July 4, 2005
  • Fusebox 4.1 For Beginners Part 4
    This four part series will introduce cf beginners to the fusebox frame work and help them get a grasp of this powerful technology.
    Author: Craig
    Views: 29,058
    Posted Date: Monday, July 4, 2005
  • Turning up the heat in Fusebox 4.1
    This tutorial teaches you some methodology and new xml tags you can use to create complex, but easy to use application in the fusebox framework.
    Author: Craig
    Views: 17,350
    Posted Date: Thursday, October 27, 2005
  • CFCs in Fusebox
    This final part in the tutorials about fusebox 4.1 will explore the use of CFCs.
    Author: Craig
    Views: 21,440
    Posted Date: Tuesday, April 25, 2006
  • Using Flash Remoting to take your CFForms Farther
    This tutorial shows you how to make a remote connection to a cfc using actionscript for your cfforms.
    Author: Craig
    Views: 23,918
    Posted Date: Saturday, July 22, 2006
  • Actionscript Basics in CFFORM
    This tutorial teaches some basic ways to achieve effects using actionscript with your flash forms.
    Author: Craig
    Views: 29,497
    Posted Date: Tuesday, February 27, 2007
  • Creating a chat system with Flex and Coldfusion
    This tutorial will cover both the Flex and Coldfusion areas of a chat application that uses the users computer to store the entire chat log and coldfusion only stores the 5 newest messages.
    Author: Craig
    Views: 17,257
    Posted Date: Wednesday, February 6, 2008
  • Creating an AIR Game
    We all want to create cool applications. Maybe you already have one in mind, but don't know how to get from start to finish. This tutorial introduces you to the AIR API and how to use it to create a simple game of chance using Flex components and a little actionscript. Below is the final product before compiling it into an AIR app. Use Flex Builder 3 to import this application so you can review it and make changes as you see fit. View Flex Builder 3 Help Docs to find out how to import an application. You can also download the final AIR application to play with. Make sure you have downloaded and installed the AIR Player from Adobe first.
    Author: Craig
    Views: 6,618
    Posted Date: Saturday, December 6, 2008
Download the EasyCFM.COM Browser Toolbar!