Archive

Archive for the ‘State’ Category

ActionScript 3.0 Flash Builder App in Apple iOS: Decorator and State

September 5, 2011 4 comments

Change orientation with device position

Change orientation with device position

Decorator and State Patterns in Mobile Game Development
While I’m trying to find the best graphic tool to use in conjunction with mobile devices and ActionScript 3.0, I’ve decided to stick with wholly programmed images. (I’m a better programmer than artist, but my images do not improve because they’re programmed.) For this example, I used the ActionScript Mobile Project option in Flash Builder 4.5.1. If you’re using Flash Pro 5.5, you can use the same code by selecting AIR for iOS from the Flash main start-up menu. With both, everything is pure ActionScript 3.0—none of the drawing tools, components or other gizmos available in either FB or FP are employed—código puro in both. Click the button below to download the files for Flash Builder. (I also included the files for Flash Pro; so no one is left out.)
kilroy

Reminder: We’ve placed all of the downloads on the University of Hartford’s Multimedia Web Design and Development download page. Just select the bottom on the ActionScript 3.0 files and click the download button.

Flash Builder Tip: First create an ActionScript Project so that you can test it as you develop. Once you have it all developed, create an ActionScript Mobile Project and just copy and paste the files from the AS Project.

Re-Decorating

In this first part all I want to do with this mobile game is to build and decorate the warrior and put it on an iOS mobile device using Flash Builder. The mechanics are very similar to previous posts on using the Decorator pattern to arm a character (See here and here.) Figure 1 shows a file diagram of the Decorator implementation:

<em><strong>Figure 1:</strong>Decorator File Diagram</em>

Figure 1:Decorator File Diagram

Since this thing is going to be in pure code, we need to create a “warrior” in code, which was not done in the previous posts linked above. So outside of the pattern, we need a graphic image, as provided in the following code:

?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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package
{
	import flash.display.Shape;
	import flash.display.Sprite;
 
	public class BuildWarrior extends Sprite
	{
		private var head:Shape=new Shape();
		private var torso:Shape=new Shape();
		private var lftArm:Shape=new Shape();
		private var rtArm:Shape=new Shape();
		private var lftLeg:Shape=new Shape();
		private var rtLeg:Shape=new Shape();
 
		public function assemble():Sprite
		{
			this.addChild(makeHead());
			this.addChild(makeTorso());
			this.addChild(makeLftArm());
			this.addChild(makeRtArm());
			this.addChild(makeLftLeg());
			this.addChild(makeRtLeg());
			return this;
		}
 
		private function makeHead():Shape
		{
			head.graphics.lineStyle(1,0x6F74B3);
			head.graphics.beginFill(0x6F91A6,.50);
			head.graphics.drawRect(30,17,10,3);
 
			head.graphics.lineStyle(0.25,0x0066ff);
			head.graphics.beginFill(0x035AA6,.40);
			head.graphics.drawCircle(35, 7,10);
			head.graphics.lineStyle(1,0x6F74B3);
			head.graphics.moveTo(30,6);
			head.graphics.lineTo(34,6);
			head.graphics.moveTo(36,6);
			head.graphics.lineTo(40,6);
			head.graphics.moveTo(32,12);
			head.graphics.lineTo(38,12);
			graphics.endFill();
			return head;
		}
 
		private function makeTorso():Shape
		{
			torso.graphics.lineStyle(1,0x6F74B3);
			torso.graphics.beginFill(0x6F91A6,.50);
			torso.graphics.drawTriangles(Vector.<number>([10,20, 60,20, 35,90]));
			torso.graphics.endFill();
			return torso;
		}
 
		private function makeLftArm():Shape
		{
			lftArm.graphics.lineStyle(1,0x6F74B3);
			lftArm.graphics.beginFill(0x6FB3A7,.75);
			lftArm.graphics.drawRect(10,20,10,40);
			lftArm.graphics.drawRect(10,60,40,8);
			lftArm.graphics.endFill();
			return lftArm;
		}
 
		private function makeRtArm():Shape
		{
			rtArm.graphics.lineStyle(1,0x6F74B3);
			rtArm.graphics.beginFill(0x6FB3A7,.75);
			rtArm.graphics.drawRect(50,20,10,40);
			rtArm.graphics.drawRect(51,60,8,40);
			rtArm.graphics.endFill();
			return rtArm;
		}
 
		private function makeLftLeg():Shape
		{
			lftLeg.graphics.lineStyle(1,0x6F74B3);
			lftLeg.graphics.beginFill(0x6FB3A7);
			lftLeg.graphics.drawRect(23,70,12,45);
			lftLeg.graphics.drawRect(24,115,10,45);
			lftLeg.graphics.endFill();
			return lftLeg;
		}
 
		private function makeRtLeg():Shape
		{
			rtLeg.graphics.lineStyle(1,0x6F74B3);
			rtLeg.graphics.beginFill(0x6FB3A7);
			rtLeg.graphics.drawRect(36,70,12,45);
			rtLeg.graphics.drawRect(37,115,10,45);
			rtLeg.graphics.endFill();
			return rtLeg;
		}
	}
}

All of the concrete decorators similarly implement coded graphic representations. Of course, all of these are “outside” of the design pattern but are useful to see in the contact of the pattern.

The Client

In the actual mobile client, you begin with a super(); call and support for auto orientation in the iOS device. The code is automatically generated:

?View Code ACTIONSCRIPT
1
2
3
// support autoOrients
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;

I tossed out the super(); call, and generated the following client:

?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
package
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
 
	public class MobileDecState extends Sprite
	{
		private var warrior:Component=new Warrior();
		private var warriorSpirit:Sprite=new Sprite();
		public function MobileDecState()
		{
			warriorSpirit.addChild(warrior.getarmor());
			warriorSpirit.x=50,warriorSpirit.y=50;
			addChild(warriorSpirit);
 
			warrior=new DecBodyArmor(warrior);
			warriorSpirit.addChild(warrior.getarmor());
 
			warrior=new DecShield(warrior);
			warriorSpirit.addChild(warrior.getarmor());
 
			warrior=new DecHelmet(warrior);
			warriorSpirit.addChild(warrior.getarmor());
 
			warrior=new DecParticleCompressor(warrior);
			warriorSpirit.addChild(warrior.getarmor());
 
			// support autoOrients
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
		}
	}
}

Publishing for Mobile

For some reason, more steps are involved in publishing for Flash Builder than Flash Pro. However, once you have your certificate (it has a .p12 extension) and your provisioning file created using the tools available to Apple developers; it’s pretty simple. If you don’t know about the Apple iOS developer program for both Windows and Mac users, you need to go there first.

Here’s how to publish using Flash Builder: (Download the Beta version/update of Flash Builder 4.5.1. While you’re at it, download the beta version of Adobe AIR 3.)

1. Open a New > New ActionScript Mobile Project (Figure 2)

<em><strong>Figure 2: </strong> Open a New ActionScript Mobile Project </em>

Figure 2: Open a New ActionScript Mobile Project

2. Specify your target platform as Apple iOS with Automatically reorient selected and click Next. (Figure 3)

<em><strong>Figure3: </strong> Mobile Settings </em>

Figure3: Mobile Settings

3. Click the Platform Setting and select Platform and Target devices (Figure 4)

<em><strong>Figure 4: </strong> Specify Platformsettings </em>

Figure 4: Specify Platformsettings

4. Build Paths provides the opportunity to add SWC folders or a project. Figure 5 shows using the default settings.

<em><strong>Figure 5: </strong> Include additional or different paths if requires </em>

Figure 5: Include additional or different paths if requires

5. The next step in creating your app will not come until you are finished coding it all. Then when you press the green arrow (Run) button at the top, you will begin the Run Configurations sequence. Figure 6 shows the On device radio button selected. You are likely to see some red circles with white ‘X’s in them, but don’t worry. If there’s one next to the Packaging setting click the [Configure] link.

<em><strong>Figure 6: </strong> Run Configurations </em>

Figure 6: Run Configurations

6. Set the Certificate and Provisioning file. Both of these should be ready using the software that the Apple iOS Developer program provides. Use the Browse buttons to locate yours. (These cannot be generated using Adobe software.)

<em><strong>Figure 7: </strong> Setting Certificate and Provisioning files </em>

Figure 7: Setting Certificate and Provisioning files

Once the certificate and provisioning file are set, click the Apply button and then click OK.

7. If all has gone right you will see the Packaging Completed window shown in Figure 8. At this point you will have to open iTunes on your computer, and make sure that your mobile device is connected to your computer. You will need to locate the .ipa package and drop it into the iTunes library. It’s easiest to just click the (Reveal package in Finder) to get the .ipa package.

<em><strong>Figure 8: </strong> Completed Window </em>

Figure 8: Completed Window

8. Figure 9 shows the bin-debug folder opened with the .ipa package. Be sure that the Apps window on your iTunes library is selected and drag the .ipa package into the iTunes library.

<em><strong>Figure 9 </strong> Drag .ipa package into iTunes Apps Library </em>

Figure 9 Drag .ipa package into iTunes Apps Library

9. The final step requires that you select the connected device (shown right above Little Richard Greatest Songs in Figure 10 ) and then find your new app in the Sync Apps window. Be sure to check the box next to the app. Then click the Apply button. Clicking the Apply button will then begin the Sync process. Once it is finished you should see the icon.

<em><strong>Figure 10: </strong>Adding the app to an iOS device</em>

Figure 10: Adding the app to an iOS device


When you click the icon on your iOS mobile device, you will see the image shown at the top of this post. If you turn your device, the object will re-orient itself to the object’s orientation.

Adding the State Design

With this and the previous posts for mobile devices, you’ve seen that design patterns work well with mobile app development. All of the advantages found in design pattern development for computers can be found in creating applications for mobile devices.

In the next post, this process will be continued by adding a State pattern to the app to create a game. If you don’t have a mobile device, you can use the same coding for making the app for your computer.

Share
Categories: Decorator, Mobile, State

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

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 ActionScript 3.0 Design Pattern Thrill Ride: Part II—Catalyst

Thrill I’ve been working on a project with Adobe Catalyst, and if I didn’t do something for a Design Pattern tour now, it would be put off until I don’t know when. So I put together a non-design pattern application incorporating video and code snippets from the Aid Game. I simply have not had time (given the work I’m doing with Catalyst) to put together a more generic design pattern “thrill ride” that I planned; so while I’m working with Catalyst, I thought I’d might as well do something with design patterns and came up with this more mild tour instead of my planned thrill ride. Figure 1 shows what it looks like:

<em><strong>Figure 1: </strong>Tour through State Design Pattern</em>

Figure 1: Tour through State Design Pattern

As you can see it’s pretty simple—sort of a PowerPoint chat. (Nowhere near as flexible as the one created with the Memento pattern.) So, if you’re interested in a mild tour, click the Play button and hop on:
play

By the way, the Catalyst project has made me far more aware of Flash Builder/Flex code. It uses Flex in its engine. If you’re interested in Catalyst, you can download the Beta at Adobe Labs. I tried importing programs (SWF files) made with design patterns, and it works great. About the only thing I didn’t do with this tour is to put the videos on Flash Media Server—sorry. I was in a hurry and wasn’t sure how to link up FMS to Catalyst. I could have written the code in Flash/Flex and created an SWF file to import into Catalyst, and that works fine, but I’m pretty pressed for time on this project.

As always, your comments and valuable feedback is encouraged. I’ll be back working on this blog as soon as I’m finished with the Catalyst project. Besides, Chandima has been writing knock-out posts to keep you interested!

Share

New Aid Game: The Machine Moves!

February 2, 2010 37 comments

Helper Class is Helped

Helper Class is Helped

I wanted to move on from the original Aid Game, at least as far as the movement was concerned; so I fully fixed it up. With the new set of rules from the previous post of repairing the movement, I realized that if I didn’t generate fully operating movement states, we’d end up overly focusing on the wrong things. So, I set up a class (TimeMachine) to encapsulate the Timer object, and then the Mover class became the child of the TimeMachine using the different TimeMachine Timer properties. Because I instantiated a Timer object in each of the properties in the TimeMachine, I do not believe it is properly an Abstract class. However, like an Abstract class, it is not invoked directly, but rather through inheritance.

Playing the Game by the Rules: First Break the Rules

The nice thing about a State design pattern is that once the rules are established, you can build your algorithms and the different states invoke them according to the rules you’ve established. You can have a number of different algorithms within the State framework, and they should all work in accordance with the rules—no matter what the rules are or what algorithms you use to invoke them.

To see if the revised game follows the movement rules, try and break the rules. The main rule that you can attempt to break is the No reverse without stopping rule. So if you’re going right and you press the Left button, your helicopter should first stop and then you’d have to press the Left button a second time. Or you can reverse direction by pressing the Stop button and then press the opposite direction. Click the Play button to give it a whirl:

play

So go ahead and try to break the rules! If you can; then the design fails. If not, it succeeds. Once you’re finishing playing, download the latest code and see how the rules were applied.

kilroy
Read more…

Share
Categories: State

Fixing the State Machine: Aid Game Repair

January 30, 2010 6 comments

Fixing a State Design

Fixing a State Design Pattern

Getting the States Straight

In a recent post to illustrate the use of composition and delegation, I created a simple game using a State design Pattern—the Aid Game. A lot of people had lots of questions and suggestions for making it better and being one who thrives on improvement and change, I promised to have a post where we’d review it as a State design pattern and not a quick and dirty example of composition.

In this post I’d like to go over some key elements of a State design and to see if we can improve on the original Aid Game by better design of state classes. Also, I’m going to leave the final repairs up to you—I’ll provide some guidelines for improved states, and you can implement them. Also, I’ll provide a little helper class that is an example of continuous movement based on one from our book that Chandima used to illustrate MVC. (I simplified it from the original; so if you look at the MVC chapter—Chapter 12—, you’ll only see pieces of it.)

Why a State Design and What are the States?

To get started, we have to ask the same key question that we should ask for every design we do. Namely,

What varies?

In moving the helicopter around in the Aid Game, the main thing that varies is the state of flight. (Each of the different directions and a stopped state represents a variation in state.) Ergo, I selected the State Design Pattern.

In our simple State design, I used five different states:

  1. Stop
  2. Move Right
  3. Move Left
  4. Move Up
  5. Move Down

Next, I’ll add some rules that were not in the first version:

  • Before reversing direction, you must first go to the Stop state.
  • If a current state is called, it cannot invoke itself.
  • Movement is continuous

Read more…

Share
Categories: State

ActionScript 3.0 State Design Pattern: An Aid Game

January 18, 2010 44 comments

Take This One to Work

Take This One to Work

After creating the post on the acquaintance relationship between classes, I started thinking about the aggregate relationship and delegation. One of the best examples of delegation can be found in the State design patterns. All of the states are delegated to objects that handle each state. So I thought it’d be a good idea to create a little game that demonstrates both delegation and a state engine at work. Then, when I do the post on aggregation relations, I’ll have a simple reference point. This one is set up so that you can put it into your lunch bucket and take it to work. What’s more, it’s designed so that you can extend it into a more interesting game.

I decided that a good starting point would be to have a helicopter fly aid packages to different places on the screen. It would start at the airport and then fly the aid to different sprite objects representing groups of people in need. However, to get started, all I did was to set up five buttons to move the helicopter around the screen beginning at the airport. Figure 1 shows what the game looks like. (It is set up on an 800 by 600 display; so I had to cut off part of the right side to fit in this blog format.) The movement buttons are in the lower left portion of the screen.

<em><strong>Figure 2: </strong> State Pattern moves Helicopter Object</em>

Figure 1: State Pattern moves Helicopter Object

Click on the Play button to get an idea of how it works:
play

Read more…

Share
Categories: State

Friends with Benefits: State and Factory Method Together at Last—Part II

In the first part of this article, Friends with Benefits: Refactoring with Multiple Design Patterns—Part I you saw how a Factory Method design pattern was used to hold and deliver data to a DataProvider object. The Factory Method design pattern allowed for easy update by simply adding items to concrete products from a Product interface (DataSupply) or new concrete Product classes. New data can be added to the Concrete Products and the Client makes requests through the Creator interface. The request is filtered through the Concrete Creator to the Product interface to the concrete Product classes. Now, all we need to do is to refactor the player with a design pattern. However, before starting download the application (With 12 classes in the design patterns, a Client class plus three folders of videos, there’s a lot!) So first off, click here to Download All Files . You can see a working version of the player and multiple data sets here. These will help pull together all of the elements used in this project.

Here Comes the Big Bad State Machine

Before we get going on refactoring the video player application, we need to see where it will go in the context of both the State and the Factory Method design patterns. Figure 1 shows the relationship between the refactored player (State) and the factory that delivers the data (Factory Method).
dualdpfilessm
Figure 1: Files for two design patterns in class diagram

The images are organized in an “open” folder, and the videos are placed in separate folders showing their relative position to the classes making up the two design patterns. The Client makes a request through the Factory Method to populate a List component with data from a DataProvider. Then, the request from the Client to the player can be made through the List component by clicking on the video selection. Figure 2 shows what the final product looks like so that you can more easily follow the refactoring:
Read more…

Share