Programming, Visualization and Game Development Theory

15Jun FlashMVC 2.0 Released!


I am very pleased to announce a major update to FlashMVC to version 2.0 with its OWN website at www.flashmvc.com! This version is a complete rewrite of the original version with better attention to scalability and framework usage. Since this is a dramatic upgrade, I have changed the package name to com.jadbox.flashmvc2. This version scales much higher allowing actions to relay complex messages to the view and built-in code hinting system for the view to execute an action. This is done by a new class called SuperAction. Let me start with the basics:

  • action classes – these are normal classes (do not need to extent any classes) that perform an action
  • SuperEvent – this class acts like a model for a specific action class, as a constructor proxy for the action class. and as an event for once the action completes.
  • SuperModel – This class holds references to SuperActions which, in turn, hold references to SuperEvents and your action classes.
  • SuperAction – This class is a controller proxy between your view and the action that it needs to perform. It allows the user to dispatch a SuperEvent that gets used as a model/constructor for your action class.

Benefits from version 1.0:

  • The action has its own model/view (SuperEvent) to inform the view
    • The SuperModel has fewer global variables as actions have their own dedicated models
  • The model (SuperEvent) also mocks the constructor of the action class for code hinting
  • Using the framework with Flash is the same exact flow you would use with Flex (or Flash Builder)
  • Much more readable code for applications made with the framework.
  • ActionHelper removed in place of SuperEvent
  • If an action doesn’t require a unique SuperModel, you can use the base class SuperEvent or make a SuperEvent that covers multiple action classes (less recommended).

Example running an action:

SuperWebsite.instance.loginAction.dispatchEvent(new LoginEvent("test@test.com));

Example reading an action:

SuperWebsite.instance.loginAction.addEventListener(SuperEvent.COMPLETE, onComplete);
function onComplete(event:SuperLogin) { if(event.isInvalidEmail) trace("email was invalid") };

Head over to www.flashmvc.com and check it out!

05May What’s New, Doc?

design-patterns-book-coverwacom-bamboo-fun-medium-tablet-cte650k-300

I have had some people asking me what I have been scheming lately which in honest hasn’t been much. The weather here in Michigan has been finally nice for a change so I have been spending most of my free time cycling. However, I did go out last weekend and finally bought the fabulous Gang of Four book Design Patterns to add to my library. I know enough C++, JAVA, and Smalltalk to decipher the examples and apply it to whatever language I might be using these days (which has been lots of AS3, haXe, C#, and Unity3D). I also decided to join the tablet bandwagon and added a Wacom Bamboo to my collection in hopes that it will inspire me to work on my art portfolio that I have been neglecting. The surface really feels (and sounds) like you are drawing on paper!

In the next coming weeks I will be working on FlashMVC to do some cleanup and perhaps add more examples to the repository.
Lastly, I have been experimenting on AI development with local unit world data deresolution and querying. Such a system I am building will allow NPCs to explore large environments while meta tagging locations of interests for latter lookups. Usually this isn’t as complicated as the process I am developing, but I have to design something that is agile and performs well in the Flash player environment. I will blog more about this soon most likely.

O, and thank you to the people who came to my lecture on design patterns last week! I hope everyone was able to walk away with some practical knowledge to apply to their own projects. There is a good chance that I might continue this lecture in the future to dive deeper into a variety of AS3-applicable development pattens. The video camera we had in the room had some issues (we lost the second half of the lecture), but I hope to get the recording compressed and posted here soon.

27Apr Detroit Design Patterns Lecture pt. 2

This Thursday, April 30th, I will be continuing my lecture on Actionscript design patterns and principles at the Detroit Adobe User’s Group meetup. See the first lecture post here for directions and time information. This week I will be covering different mainstream design patterns in detail and if we have time give a brief overview of popular MVC frameworks that help accelerate application development. However, I do believe that teaching patterns and frameworks without knowing good object oriented principles is fruitless so I will also continue this topic discussion into the next portion of the lecture.

The conference is free to attend, and anyone from beginners to experts are welcome to join!

07Apr FlashMVC Update: addResultListeners

flashmvc

I have just finished up making another addition to my framework FlashMVC. The update effectively removes the need to use ActionBinder as I will indicate below. ActionBinder was a neat utility, but ultimately I wanted solution that was just as simplistic but could be usable for both Flash and Flex. I couldn’t find any easy solutions until I thought about retrofitting addEventListener with an alternate form to allow callback functions to fire for specific commands on the SuperModel. Hence, I have added these three new methods to SuperModel:

.addResultListeners(actionName:String, onSuccess:Function, onFail:Function)
.addStatusListeners(actionName:String, enabled:Function, disabled:Function)
.addHasActionListeners(actionName:String, added:Function, removed:Function)

Now in your view, you can do something like this in your view:

var app:MySuperApplication = MySuperApplication.getInstance();
app.addResultListeners(MySuperApplication.Login, onSuccess, onFail);
// SuperModel.perform(name of the action, optional onComplete function, ...Rest for the parameters of the action class)
app.perform(MySuperApplication.Login, null, "test@invalidemail@.com");

function onSuccess(result:*):void {
   trace("Login was successful");
}
function onFail(result:*):void {
   if(result==MySuperApplication.RESULT_INVALID_EMAIL)
         trace("invalid email used");
}

Updated ASDocs Here

Aside from this addition, I added in some safeguards like throwing an error if a command tries to call ActionHelper.complete() more than once as well as some other fixes. ActionBinder is still useful in the Flex world as it can help increase readability in some cases, but SuperModel now has most of the nice features built into it.

Please let me know if you have any comments! I am still working on adding in the replay feature to the framework which hopefully I will have done soon.

Tags:

27Mar Further Reading on Design Patterns

As a followup on my Wednesday lecture on design patterns, I wanted to post some informative resources for learning more about design patterns outside the next lecture on the topic. Also, I wanted to say thanks for everyone who showed up to hear me rant about code structure (not the most exciting topic in the world mind you)!

Design Pattern Definition
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.
- read more at WikiPedia

MVC Definition (the most common principle of Design Patterns)
mvc
Model–View–Controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model.
- read more at WikiPedia

Books:

AS3 Design Pattern Informational Websites:

Flash Design Pattern Frameworks:
(for now, it’s best to avoid these until you understand the fundamentals of MVC)

Good Design Priniciples:

  • ALWAYS type your variables (not really design principle but I too often see people doing this still)
  • An object/MovieClip should contain the actions that it performs (as oppose to objects outside the class forcing it to perform actions)
  • A class should never be able to “break” if the user sets a property or calls a function on it when they are not suppose to. Keep preventive logic in the class that’s doing the work.
  • A good chosen design pattern for a problem will not take any longer to implement than not using it with spaghetti code.

Feel free to leave comments or email me about any further questions you have about Design Patterns or where to find additional materials on it. Have a great weekend everyone!

25Mar Detroit Design Pattern Seminar

DAAUG

On Thursday 3/26/2009, I will be giving an open seminar on design patterns for the Detroit Adobe User Group. I should have blogged about this much earlier but my free time has been spread thin of late unfortunately. It will be hosted at ePrize starting at 7:00pm and ending about 9:00pm. I will be covering just some introductory topics of good programming practices with AS3 while diving into some design pattern concepts. There is also a good chance that I will do a more advanced seminar on design patterns in the near future at the user group meetings. This conference will be free to the public so please leave a comment or shoot me an email for directions or more information.
-[ Jonathan_Dunlap::email="jonathan AT jadbox.com" ]-


View Larger Map

21Feb FlashMVC API Update

While having time this weekend to review a few of the Flash projects I’ve been working on, I became aware of the idea that every software “action” has the anticipated state of failing. Login will fail if the user enters incorrect credentials or leaves a field empty; A user cancels a file copy operation; A reg form may fail if the user is not permitted to enter the site based off their information. It’s not that the application is failing because it can’t reach a web service or something unexpected happened, but rather a planned reaction was developed to give the user a negitive response to their action. In light of this, I have updated FlashMVC to allow actions to designate that it’s result is negitive/failed. Then on the SuperModel side, the view can optionally supply a fail callback function for when the action designates that it failed.

//  Action class
public class Login {
    public function Login(helper:ActionHelper, name:String, password:String) {
        if(name=="user" && password=="pw") {
            SuperSimpleApp.getInstance().userFirstName = "John Doe";
            helper.complete();
        } else {
            if(name=="" || password=="") helper.result = SuperSimpleApp.RESULT_EMPTY_FIELDS;
            helper.complete(false); // "false" tells the caller that this was not successful
        }
    }
}

The line “helper.complete(false)” tells the SuperModel that the action completed but it was a negative response. In this example, it was failing the login action. So we have the action created, now we need to create the SuperModel that its attached to and the SuperModel will also service as its model.

// SuperModel
public class SuperSimpleApp extends SuperModel {
    public static const LOGIN:String = "Login"; // String reference to the class name for the view to call
    // Flag a response to use in special situations where the view needs to know more about the result
    public static const RESULT_EMPTY_FIELDS:String = "emptyFields";
   
    public var userFirstName:String;
    public function SuperSimpleApp() {
        // Register the class to the SuperModel for use.
        // Note: once the action is added, use the string name of the class to reference it
        actionAdd(Login);
    }
    public static const getInstance():SuperSimpleApp = new SuperSimpleApp();
}

Now in Flash or in your Flex MXML you can run your Login action like this:

var superModel:SuperSimpleApp = SuperSimpleApp.getInstance();
// loginAction will hold the action class we want to call and setup the onSuccess and onFail callbacks.
var loginAction:Performance = new Performance(SuperSimpleApp.LOGIN, onSuccess, onFail)
// ...
// Now later in the code, run the action now on the SuperModel with a test username and password
function onSubmitButtonClick(e:Event) {
    superModel.process(loginAction, "user", "pw");
}
// If the user is logged in successfully
private function onSuccess(result:*):void {
    trace("Hello "+ superModel.userFirstName);
}
// If the login action designated a negative response to the request:
private function onFail(result:*):void {
    // Check the result against known responses flagged in the super model... otherwise give generic message.
    if(result==SuperSimpleApp.RESULT_EMPTY_FIELDS) trace("Please fill out all fields");
    else trace("Invalid username or password");
}

This should help having to deal with common success and fail responses from actions. Let me know what your thoughts are!

Tags: ,

13Feb AS3 Best Practice for Callback Evals

Callback pun

UPDATED: Thanks to my readers- there is an even easier way to evaluate a function as being not null without a compiler warning. One suggested a method using a type check (functionName is Function) however this is process intensive task for the compiler especially if this has to be done within a game loop. I believe the most efficient solution was suggested by Mije for doing a strict comparison by !== against null. This is better than != as the previous evaluation executes faster.

One of the techniques I am fond of is callback functions when using a custom event may be overkill for the situation. However, trying to actually explain callbacks verbally is almost impossible. In a nutshell, it’s a method (lets say A) that accepts another a method (lets say B) as a property. Method A will perform its action and then call method B. This allows the class that uses Method A to have one of its methods called once Method A completed.

Here is an example; however, in practice, callbacks are only useful when the method that uses it is in a different class otherwise you could just call the method directly instead of using the callback.

// Example function that calls the method that uses a callback
private function gameEnded():void {
saveScore(10, onSave);
}
private function saveScore(score:int, onSaveCallback:Function):void {
// saving score...
// once done:
onSaveCallback();
}
// This is the function that gets past into saveScore
private function onSave():void {}

Okay okay, now here is the problem at hand. What if the callback function was optional? You could write it like this:

// onSaveCallback is now optional with a default value of null
private function saveScore(score:int, onSaveCallback:Function=null):void {
onSaveCallback();
}

Not so fast! If the callback function is not specified and gets set to null, Flash will throw an error since you cannot call null as a function like this: null().
Well, you could do a conditional check:

// onSaveCallback is now optional with a default value of null
private function saveScore(score:int, onSaveCallback:Function=null):void {
if(onSaveCallback) onSaveCallback();
}

This way we can check to see if onSaveCallback does not equal null. Well, this angers the Flash compiler and it will throw the below message:
Warning: 3553: Function value used where type Boolean was expected.  Possibly the parentheses () are missing after this function reference.
This is because Flash is confused that you are trying to evaluate a function as a Boolean instead of using it normally as a function. So, how can we evaluate if the function is not null without throwing a Flash warning? Well, I scowered the internet and could not find a best practice for Flash. After a discussion with my readers, the best solution here is to do a strict type check to null as shown below:

private function saveScore(score:int, onSaveCallback:Function=null):void {
if( onSaveCallback !== null ) onSaveCallback();
}

Well there you have it- let me know if this works for you!

Tags:

01Feb ActionScript Reference for Android!

ActionScript Reference for AndroidAfter seeing that someone wrote an ActionScript reference application for the iPhone called ActionScript 3 API Reference for iPhone, I decided to take matters into my own hands and make the same application for the Android platform which the t-mobile G1 works on. The Android OS is a fantastic platform for a developer as I made this whole application over just two weekends. For the first release, I included a view to see all classes and a class search functionality. You can now download this from the Market on your Android phone! You can find it under the Application – Reference section, and it’s called ActionScript Reference. See the below screenshots…

Classes View:
screen1

Class Information View:
screen2

For more information on Android: http://www.android.com/

Tags: ,




Bad Behavior has blocked 307 access attempts in the last 7 days.