Archive

Author Archive

Flash Builder Mobile ActionScript 3.0 Design Pattern

Flexible Design Pattern Re-used with Flash Builder Development

Flexible Design Pattern Re-used with Flash Builder Development

Easy Update

A couple of days ago, we had an example for beginners creating a mobile application using Flash Professional. We used an Android example because everyone can get the tools they need for emulating an Android. (By the way, partnering up with Google-Android and Flash was a brilliant move by Android. Being an “Apple Guy,” I thought I’d be doing nothing but apps for my iPhone and iPads; however, Android made it a lot easier to develop apps for Android using some kind of ActionScript 3.0 development tool, and Blackberry’s not far behind. So I am very happy to know that iOS is now available, but they’ll just have to wait their turn for a beginner’s post.) As promised, I wanted to create a beginner’s example using Flash Builder. This example uses the same Strategy Pattern as the Flash mobile tutorial. However, as you will see, there are some key differences when dealing with Flash Pro and Flash Builder. Also, I hope you see that a very different logo (FB instead of Sandlight) and text. All that was changed for this difference was swapping the image used for the logo and the text in the external text file. Also, I had to change some settings in the BringText class, but that too was easy and didn’t upset the program. Why? Because it was a design pattern!

Stepping Through Flash Builder Mobile

This is going to be the same walk-through with Flash Builder as with Flash Pro but with a few differences. The Flash Builder work flow is slightly different, but you will find more similarities than differences. Before we get going download Flash Builder 4.5.1. (You can use the 30-day free trial version.) You can probably work with FB 4 with all of the updates, including the Android SDK, but everything in this example was done with FB 4.5.1. (If you are a student or faculty, you can get a free educational version of FB if you contact Adobe with your student or faculty ID. Faculty can get it free for their classrooms and labs as well.) Install to the defaults. Go to Adobe Labs download and install both Adobe AIR 3 (beta) and Adobe Flash Player 11 (beta) and let’s get started:

First, open Flash Builder and select File > New > ActionScript Mobile Project. (Note: You will find both a Flex Mobile Project and an ActionScript Mobile Project; be sure to select ActionScript Mobile Project.) In the Project name window, name the project FBmoStrat as shown in Figure 1 :

<em><strong>Figure 1:</strong> New ActionScript Mobile Project window</em>

Figure 1: New ActionScript Mobile Project window

I used the default location and the default SDK, which was Flex 4.5.1. Click Next.

Second, when The Create an ActionScript Mobile AIR Project window appears with the Mobile Settings tab selected, you will see that all Target platforms (Apple iOS, BlackBerry Tablet OS and Google Android) are checked as shown in Figure 2.

<em><strong>Figure 2:</strong>Initial Create Window</em>

Figure 2:Initial Create Window

Third, uncheck both the Apple iOS and BlackBerry Tablet OS. When you do that, the Permissions for Android appear as shown in Figure 3:

<em><strong>Figure 3: </strong> Android Permissions</em>

Figure 3: Android Permissions

Be sure that the Platform is Google Android and that the only permission checked is INTERNET. The default is to Automatically reorient the screen in the Application settings. Leave that default checked and click the Next button.

Fourth, in the Build Paths step, you will see a set of default selections you can leave alone except for the Main application file that you want to change from FBmoStrat.as to Client.as. Figure 4 shows the step correctly configured:

<em><strong>Figure 4:</strong> Build Paths step</em>

Figure 4: Build Paths step

If your Build Paths steps looks like Figure 4, click Finish. You should see the following script automatically generated:

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
 
	public class Client extends Sprite
	{
		public function Client()
		{
			super();
 
			// support autoOrients
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
		}
	}
}

The Stage Align and StageScaleMode built-in ActionScript 3.0 classes will help align the application when it is turned in different directions. The super() method invokes the parent class Sprite. You will be leaving the constructor function as is but add more materials for the Client class. Before doing that, go ahead and test the problem and download all of the files with the buttons below:
playkilroy

You still will need to test the file from Flash Builder and contend with one last set of settings. So gather up all of the files and read on before testing.

Read more…

Share
Categories: Mobile, Strategy Pattern

Beginning Mobile ActionScript 3.0 Design Patterns with Flash

ActionScript 3.0 Design Patterns in Mobile Apps

ActionScript 3.0 Design Patterns in Mobile Apps

Get Your App Up!

The very first mobile app I want to build is one that I can give away to promote my company or my clients’ companies. Yes, I’d like to make lots of money with a mobile action game like Angry Birds, but in order to get started, I want something that I can easily update and change. It seems like every time I check my phone apps, I’ve got updates. What is one of the main features of Design Patterns? Easy updates! So, if you want to create mobile applications in ActionScirpt 3.0 that are easy to update, you’ll find design patterns your BFF!

This first one is built with Flash CS5.5. If you do not have Flash CS5.5; download the 30-day trial version. If you’re using Flash Builder, use FB 4.5.1. or download the trial version. (I hope to have a FB tutorial using this same example later in the week. In the meantime, take a look at Christian Peters’ mobile example for building an app using design patterns with Flash Builder.)

This first example uses a Strategy pattern with algorithms for loading external images (or .SWF files) and text. That is exactly what I need for a mobile app promoting my company. With the image loading capability, I can load my logo and any images that show off products and services. The concrete text strategy loads up data from external text files. So this ought to be the easiest app to update imaginable!

Easy Android

I was going to start off with an iOS example, but I realized that most of you probably didn’t want to shell out the $99 developer fee required by Apple for iOS development. So, instead I decided to use an Android example that you could test using an Android emulator. To get started, go ahead and download the source code and see what the app displays:
playkilroy

All of the Downloads have been moved to the University of Hartford’s Multimedia Web Design and Development Program page. The last entry under “ActionScript 3.0/ Flash” should have what you want. (I’m still working on it to include a short description of each entry–it’s in the database; just not on the screen).

When you run it, you will quickly see that a logo and block of text pops up. That’s it. Swap out your own logo and texts, and you’re in business. You can change any of the parameters in the BringText concrete strategy class to alter the text appearance, it’s placement and other features to suite your own tastes or business brand.

Starting from Scratch

Since this is a first time experience for beginners and mobile (which may include experienced ActionScript 3.0 programmers), we’ll step through the set-up beginning with the FLA file. So read on through the following steps:

Read more…

Share
Categories: Mobile, Strategy Pattern

Video Game State Machine:No Conditionals Part III

State Video Game!

State Video Game!

State Design Pattern Game

Is the State Pattern the way to go with a game based on videos? First, we have to ask, what varies? In this case, different places on the grid represent different situations in a game environment and depicted in a video. (Actually, any environment that requires unique states presented in videos–such as a guided tour of a museum–would be ). Simply put, the videos vary and each represents a different state. So the answer to the first question is, yes, the State pattern is appropriate.

Second, we must ask, are updates and changes easy with this application of the pattern? In this particular case, I tested several different videos with this applications, and it’s very easy to swap and change videos. In fact, if I want to use .SWF files for animation instead of videos, that too would be a cinch.

Third, we need to consider the code generated. Will using the State pattern generate more code and more work than other patterns or coding strategies? This may be the Achilles’ heel of the pattern used as a game generation design. Consider the following:

  1. Each grid cell is a state
  2. A 19 x 19 grid generates 361 cells
  3. Each cell needs a State class
  4. The grid requires 361 State classes
  5. The Context class requires getter methods for each class
  6. The Context class generates at least 1,444 lines of code (assuming each method takes up 4 lines)
  7. The Context class constructor function requires an additional 361 statements to instantiate instances of each state

If that looks like a lot of code and classes, it is. However, design patterns were originally created to ease the task of very large programs, and just about any way you work it out, 361 different states (video shots) is going to be difficult to keep track of. The biggest problem I can see in this design is in the Context class. The Context keeps track of what state the user is currently in. When states change (and you’ve got 361 of them), you have to include a method in the Context for changing states. There’s where you end up with a very big class. Before going on, though try playing the game and download the files using the buttons below: (By the way, this time there’s a surprise…see if you can find it in the play..be careful, it’ll eat you.)
playkilroy

*Reminder: I’m putting all of the downloads into a general download site stored under “ActionScript 3.0″; so, just click on the latest download and you’ll get all of the files, including the videos and even the Excel spreadsheet with the direction grid.

Read more…

Share
Categories: State

Video Game State Machine:No Conditionals Part II.5

A Better State is at Hand

A Better State is at Hand

A Dot Release

In our previous post on the State Design Pattern, I wanted to have a nice clear example, but in the process, too many parts were left out, and in some respects it was more complicated with the use of the helper class (Distributor) than it had to be. As a result, the design generated multiple instances of the Distributor class and each instance was difficult to control—not to mention the fact that each new instance overloaded the program with unneeded instances. As a result, I decided to simplify the video process by creating a single instance of the Distributor in the Client and just pass the name of the requested video to be played through the same instance using the Distributor’s methods. So instead of having each state return a Sprite instance, they now return a String instance used by the single Distributor instantiated in the Client. The following buttons provide the new files to download and running example:
playkilroy

*Note about Downloads: I’m in the process of moving all of the downloads to the MWDD site at the University of Hartford. It’s still being set up, and I’m working on a way to provide more information about each of the downloads. All of the downloads for this blog will be under ActionScript 3.0/Flash (which includes Flash Builder/Flex).

Secondly, the first example just included two states—one for starting and one for going one step to the east. That helped keep things simple, but it didn’t do much for seeing how the State design pattern can handle the North-East-West-South (NEWS) directions. Figure 1 provides a statechart that shows an NEWS state machine with an additional state to the east. It provides a better idea of where the State pattern can take us.

<em><strong>Figure 1: </strong> Statechart of Direction Relative States</em>

Figure 1: Statechart of Direction Relative States

The statechart shows movement between states and the kinds of transitions relative to a starting position.
Read more…

Share
Categories: State

Video Game State Machine:No Conditionals Part II

Starting State Design Patterns

Starting State Design Patterns

Help for OOP/DP Beginners: Rewind the State Pattern

I started working on the State design pattern, and I realized how easy it is to quickly get lost. The idea of a state machine is pretty clear and simple, and so is the State Design Pattern. However, I find that if I’m away from it for any length of time, it gets all tangled up again—like fishing line in a well-used tackle box. So, in this inserted post between Part I and Part III of the Video Game Machine series of posts, this one is for beginners in the State design pattern.

The two examples used are simple, but both have to get through the tangle of the requests from the Client through the Context requests and on to the concrete states via the State interface. The first example is wholly abstract but really simple. Play and download buttons provide access to get started:
kilroyplay

Overview

Figure 1 shows the State class diagram and the ActionScript 3.0 files so that you can easily see the implementation of the pattern. The Client makes a request for a given state through the Context. The Context checks the current state (think lights on; lights off as two distinctive states) and then requests the action from the current state. So, if current state is lights on and the request is to turn on the lights, it wouldn’t do anything because the state already exists.

<em><strong>Figure 1: </strong> Class and File Diagrams of State Design Pattern</em>

Figure 1: Class and File Diagrams of State Design Pattern

Rather than turning the lights on or off, this example starts with a “Starting” state and a state known as “East1.” So the user is either in the Start State or the East1 State. These two states will be abstract with trace() statements in this first example that helps to see what’s going on, but in the second app in this post, we’ll use videos. Once the State design pattern is established, it’s very easy to add and change objects without crashing the application. That’s what makes the State pattern so valuable; a little extra work at the outset pays huge dividends in the long run.

The Participants

The State design pattern deals with variation in an object’s state. An adventure game can be treated as a series of states that the player enters and leaves. Depending on the state (situation) different things are possible. The state can change from the home base, to the wizard’s fortress to the jungle to an underground cavern maze, into and out of a worm hole, a parallel universe or anything the developer’s mind conjures.

The most important work in the State pattern is Context class. It keeps track of the current state to determine how to handle a request. Imagine three states known as:

  • State 1
  • State 2
  • State 3

State 1 can only remain in its current state or go to State 2. It cannot go directly to State 3. So if the Client requests State 3, the Context realizes that the current state is State 1 and so makes the call to State 1 where the options available in that state do not include a move to State 2.

The determinations are not made using conditional statements. Rather, as each state is called, it reports to the Context establishing itself as the current state. As a State pattern application grows in size, it must generate a separate concrete state for each new situation and possible changes in state. The State interface requires a new method for accessing the new states, and the concrete states must include that method in their structure—even if the method results as a null one. For example, in the State 1 concrete state class, the method to go to State 3 does nothing.
Read more…

Share
Categories: State

PureMVC Goes Mobile 2: MVC-driven & ready-to-compile Mobile Application with the Flex Framework! by Christian Peters

Make ActionScript Design Patterns Mobile

Make ActionScript Design Patterns Mobile

Gentle Readers: This is the second part of a post on using ActionScript in a mobile environment by our guest blogger, Christian Peters who maintains a blog at http://digitale-avantgarde.com. He was kind enough to translate his post from German into English. (For those of you who would prefer the original German version, visit Chris’ site.) Because of the size of the post, we’ve had to divide it into two separate posts. The first half of this post is can be found in the previous posting. We and Chris would appreciate your comments.

Registering Mediators

If you look back at our ViewNavigatorApplication at the beginning, you’ll notice, that I’ve added an initial view:

1. firstView="com.digitaleavantgarce.view.components.HomeView"

This is the first view and the ViewNavigator sets it as the active view at the beginning.
I’ve moved it from the default package to a package that is more compliant to my overall structure.
It can be any view you like, but let’s say it has a button with the label “Click me” in it. It should read something like this:

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1.	<s:view xmlns:fx="http://ns.adobe.com/mxml/2009"
2.	                xmlns:s="library://ns.adobe.com/flex/spark"
3.	                initialize="onInitalization(event)"
4.	                title="Getting Started">
5.	        <fx:script>
6.	                < ![CDATA[
7.	                        import mx.events.FlexEvent;
8.
9.	                        public static const NAME:String = 'HomeView';
10.	                        public static const CLICKED:String = NAME+'Clicked';
11.
12.	                        protected function onInitalization(event:FlexEvent):void
13.	                        {
14.	                                this.id = NAME;
15.	                        }
16.	                ]]>
17.	        </fx:script>
18.	        <s:button label="Click me" horizontalCenter="0" verticalCenter="0" click="dispatchEvent(new Event(CLICKED));"/>
19.	</s:view>

This should be familiar, but note two things:

First: Since the View does not have a name Property and I don’t want to implement an interface, I make sure that the id is equal to the NAME constant on initalization!

Second: When the button is clicked, it’s dispatching an event named CLICKED. Remember, that the views should not host logic, they just should forward the action to the framwork. Thus, a mediator should take care of the action.
Read more…

Share
Categories: Mobile, PureMVC

PureMVC Goes Mobile 1: MVC-driven & ready-to-compile Mobile Application with the Flex Framework! by Christian Peters

Optimizing Mobile Apps with Design Patterns

Optimizing Mobile Apps with Design Patterns

Gentle Readers: Every now and then Chandima and I have a guest post. In this case, Christian Peters who maintains a blog at http://digitale-avantgarde.com was kind enough to translate his post from German into English. (For those of you who would prefer the original German version, visit Chris’ site.) Because of the size of the post, we’ve had to divide it into two separate posts. The second half of the post will be available next week. We and Chris would appreciate your comments. Click the download button to get the entire code:
kilroy

PureMVC Goes Mobile

Let’s build a cross-platform compatible, MVC-driven & ready-to-compile Mobile Application with the Flex Framework!
A year ago, finding people who bet serious money on Flash missing a connection to the mobile world was an easy task. This is no longer the case nowadays. Adobe has introduced an iOS Compiler and AIR for Android & Blackberry Playbook. With the latest release of Flex SDK 4.5.1, the average Flash-Coder is transformed to a crossplatform-ready mobile developer. Amazing times. Let’s look at how to adjust the Standard Port of the famous PureMVC Framework to be mobile-ready! The Flex SDK ships with an integrated Navigation for Mobile Views, the ViewNavigator. There is an excellent introduction to the topic, that can be found here, but I’ll give a brief overview about the concept:

Mobile Applications – especially on Smartphones – are restricted in a very important feature: Space. If you adapt a Web app to mobile, you’ll typically have much more views because you have to present the same content on smaller displays. Flex comes to the rescue by introducing the ViewNavigator. The ViewNavigator is a container, that holds references to the available views and makes navigation between them easy. You can imagine it as an array – where the view at the zero index is visible & active. It’s not a coincidence that the ViewNavigator has array-esque methods like popView() or pushView()!

The ViewNavigator is a nice way to handle views, because it’s an easy way to navigate through an app: Every view holds a reference to the ViewNavigtor – the navigator property – and can forward the application to another view on demand.
Well, it’s not all roses with the ViewNavigator! A view has its own control-mechanism as property – while it should be vice versa. Another downside: The registering and instantiation of views are becoming tasks of Flex, while you normally want to handle those tasks in your infrastructure framework of choice! Mine is PureMVC. I want to show you a way to hook PureMVC to the registering process of the ViewNavigator to build nicely decoupled applications for the mobile world. Some experience with PureMVC is recommended, but I’ll give you a quick …
Read more…

Share
Categories: Mobile, PureMVC

We Need to Talk: Should We Take AS3 DP Mobile?

Design Pattern Development on Mobile

Design Pattern Development on Mobile

What a Difference a Year Makes

A little over a year ago we posted a lament about Apple freezing Flash/ActionScript 3.0 out of their mobile market. In re-reading that post, I was surprised by how prescience some of the comments were. HTML5′s implementation would be all over the map and the debate about H.264 vs. VP8 is as heated as ever. More importantly though, rather than sitting on their hands and wringing their crying towel, Adobe made adjustments to Flash (Both Builder and Pro) and ActionScript 3.0 to deal with the new realities. The recently released Flash Builder 4.5.1 and AIR 2.7 can deal with the most popular mobile protocols.

I realized that we recently began adding posts on parallel programming and got off to a roaring start, but interest waned in that topic as some of the readers realized that AS3 didn’t have the kind of programming resources that other languages had (such as C#) and we were sort of working with a DIY version of parallel programming. I believe that in the next version of AS3, we may be seeing classes where we can directly process multi-threaded programs. Likewise, we began doing Design Patterns and OOP for Beginners, and we’ll continue with those posts.

The idea of adding posts on mobile development involves two issues. First, creating apps for mobile devices is a topic unto itself due to the protocols involved. Second, some new classes in AS3 are specifically for either AIR and/or mobile devices (The new CameraRoll class is an AIR/Mobile class.) So we may have some examples that would be awkward for non-mobile developers. However, we’d try to keep things more universal by suggesting non-mobile alternatives. This is not a proposal to shift to mobile-only AS3 design patterns. Rather it is a proposal to ease into a combined mobile/non-mobile Flash set of examples using design patterns.

Obviously, we’ll need some basic starting points for mobile development, primarily in Android and iOS formats, but we’re pretty new at mobile development ourselves; so it will be in baby steps. Besides, books are becoming available. Véronique Brossier’s book, Developing Android Applications with Adobe AIR: An ActionScript Developer’s Guide to Building Android Applications, (sample chapter) and Matthew David’s new book, Flash Mobile, are resources available for getting up to speed with mobile Flash and ActionScript 3.0.

Anyway, we’d like to get your feedback. Should we start including mobile examples? Yes or No? Use the comments section to share your thoughts.

Share
Categories: Mobile

What if ActionScript 3.0 had no Conditional Statements? : Part I

Think in Non-Linear Concepts

Think in Non-Linear Concepts

On a couple of occasions, we’ve discussed working without conditional statements. You may recall that both the Strategy and State design patterns have no conditional statements, and so the idea isn’t particularly new. The issue came to mind when I was unraveling a PHP program that had nested conditional statements used in pulling out table data. Even though they seem to crop up like weeds everywhere, nested conditionals and loops represent poor practices . (Dave Shuck’s solution for refactoring nested conditionals is worth a look.)

Other than the fact that nested conditionals can create the worst kind of object binding as each condition sends the program further down the binding rabbit hole, we seem to really need them for working out certain kinds of problems. For example, in a visual game scenario, the user may be faced with choices. Suppose the game state is a crossroad where the player must choose to go North, East, West or South (NEWS). Alternatively, the choice may be video perspectives of different directions. Any one of the choices carries with it a whole set of other states, conditions, capabilities and properties.

One way to handle this kind of choice is with a conditional statement. The following shows two things. First, it shows that when a direction is selected, it typically has more than one thing being affected. (The more than one thing is furnished by “Everything else.”) Second, the binding for each is represented by the conditions within each conditional. (You could do the same thing with a Switch statement, but the binding wouldn’t change.)

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package
{
	import flash.display.Sprite;
	public class NEWS extends Sprite
	{
		private var newsArray:Array = new Array("north","east","west","south");
		private var dir:Object;
 
		public function NEWS()
		{
			for (dir in newsArray)
			{
				if(newsArray[dir]=="north")
				{
					trace("Hellloo Siberia");
					trace("Everything else....");
					trace("");
				}
				else if(newsArray[dir]=="east")
				{
					trace("Visiting Bejing");
					trace("Everything else....");
					trace("");
				}
				else if(newsArray[dir]=="west")
				{
					trace("Dude! You made it!");
					trace("Everything else....");
					trace("");
				}
				else if(newsArray[dir]=="south")
				{
					trace("¡Recepción a la Argentina!");
					trace("Everything else....");
					trace("");
				}
			}
		}
	}
}

That certainly can solve the issue of generating different responses from different object properties. It’s compact and saves ground-fills of wasted bits. It illustrates a common method of dealing with multiple options. The loop iterates through the object, and each iteration is examined by four conditional statements.

Unconditional Programming

Let’s go back to the NEWS example, and instead of having trace statements representing different directions, this next example uses short videos pointing in different directions. (I live in the woods so the videos are fairly woodsy—but they show the four points of the compass—honest.) I want to make an app with four buttons that plays a video pointing in the selected direction. Plus, I don’t want to use any conditional statements. (Easier than you think.) Click the Play and Download buttons to see a working example and get the code and videos.
playkilroy

In the next section where we examine the code you will see two things: No conditional statements and a non-linear solution. The user has several choices, and simply by making a choice she/he goes directly to the object desired—a directional video.
Read more…

Share

The Warrior's New Clothes: Using AS3 in Flash Builder to Create Sprite Graphic Classes

Code your own Sprite classes

Code your own Sprite classes

Sprite Classes in Code

When I’m working on an example, I’ll use a combination of Flash Pro and Flash Builder. However, using Flash Pro, all of my drawings are in the Flash Library and may not be accessible to Flash Builder users. Besides, my drawings are pretty simple composed of basic shapes—rectangles, circles and triangles. These images are transformed into Sprite classes in the Symbol Editor of Flash Pro, and the type is changed from the default MovieClip to Sprite. If I coded the images as Sprites using ActionScript 3.0, the Flash Builder users would be able to more easily use them and the Flash Pro users could use them with equal ease.

Let’s face it, my graphics are not going to get any better whether I code them or draw them; so why not code them? So that’s what I’ve done. In the previous post on the Decorator design pattern for beginners, I had three graphic “armor” pieces that were used with concrete decorator classes. All I’ve done for this mini-post is to provide the “armor” sprites as pure code. From now on when I have a Sprite image, I’ll just code them up in ActionScript 3.0 as Sprite classes and make it easy for everyone. Here’s the Shield, BodyArmor and Helmet classes: (Next page.)
Read more…

Share