Programming, Visualization and Game Development Theory

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: ,

26Jan FlashVars for EVERYONE!

flashvarscatWhen building utilities that can be used with both Flash and Flex, there are two common hurdles that developers run into. The first one is that Flex does not pull FlashVars the same way that Flash does. This means for ActionScript utilities that rely on html inserted variables will need to be separated into two separate files or need to have flashvars passed into the utility from the outside. Another hurdle is that Flash does not have a global reference to Stage- instead it can only be accessed through display children of stage. This is problematic for utilities that work with Stage as they can only get there reference of stage when it’s manually passed into the utility as a parameter which can result in an ugly web of stage references being passed around.

However, I finally got the time to develop a workaround that solves both problems with classes FlashVars and StageReference. The tricky part of this implementation was building a utility that could use the class Application but not reference it when it was being built from Flash since it would cause the compiler to fail from the invalid class reference. I worked around this issue by grabbing Application by getDefinitionByName so that the Flash compiler wouldn’t fail since it was a weak reference.

With Flash, use StageReference.stage = stage in Frame 1 or in your document class’s constructor. This will give you the global reference to stage and also allow the new class FlashVars to pull flashvars automatically when compiled in a Flash project.

The custom class FlashVars is used in this fashion:

var myFlashvar:String = FlashVars.parameters["myFlashvar"];

or

var myFlashvar:String = FlashVars.parameters.myFlashvar;

This usage is exactly the same from Flash and Flex! No more having to switch from loaderInfo.parameters to Application.application.parameters when porting utilities between Flash and Flex.

Download (includes StageReference): flashvars.zip

(more…)

Tags:

16Jan Object to URLVariables

ninja_vs_pirate_by_cookiemagikLooking back at my last few blogs, I seem to have been neglecting to post ActionScript related stuff even though I have been more development than ever. It’s probably due to the fact that since I work with it all day that I lack the ambition to blog about about it.
One of the many great things working with Flex is being able to use HTTPService which is a very neat utility. So one day I was working with pure Flash and discovered that URLRequest data property only really allows URLVariables object (and ByteArray for those who do their homework). HTTPService on the other hand can take in raw Object and parse all its properties (including dynamic ones) into a POST payload. With a little digging into HTTPService, I extracted the code it uses to parse and object that I used to build the below function that will convert an Object into a URLVariables object so that you can send it with URLRequest.

Updated: This will work in any version of Flash AS3 now.

public static function objectToURLVariables(parameters:Object):URLVariables {
            var paramsToSend:URLVariables = new URLVariables();
            for(var i:String in parameters) {
                if(i!=null) {
                    if(parameters[i] is Array) paramsToSend[i] = parameters[i];
                    else paramsToSend[i] = parameters[i].toString();
                }
            }
        return paramsToSend;
}

(more…)

Tags:

09Dec flashMVC: New Utility ActionBinder!

I just update the SVN (svn.jadbox.com/public/) source for flashMVC with a MXML component tool I made for the cases that I was working with Flex. It’s located in com/jadbox/flashMVC/flex/ActionBinder.as, and it helps automate the view (aka MXML) portion of your application to communicate with your SuperModel. It will monitor the status of a particular action on the model, and allow the user to easily perform view updates or to run the action itself. This will help further reduce the amount of work you will have to do in Script tags (if not completely remove the need for one in the MXML).

// Example
<flashMVC:ActionBinder superModel="{mySuperModel}"
    action="{mySuperModel.LOGIN}"    
    id="LoginBinder"     
    actionComplete="{trace('Login action completed')}"   
    actionEnable="{trace('action enabled')}"     
    actionDisable="{trace('action disabled')}"   
    actionPerforming="{trace('working')}"    
    actionStoppedPerforming="{trace('stopped working')}" />

// You can also do the action from the wrapper:
myActionBinder.perform(...args);
LoginBinder.perform(username.text, password.test); // for example

// Can use this property to
// enable or disable the action as well:
myActionBinder.actionEnabled=false;

You can find a great example of this in my SVN under the path:
/flex projects/flashMVC examples/actionBinderExample/
You will just be sure to link the flashMVC framework from the Flex project settings to compile.

Asdocs have been updated with the ActionBinder’s API. For more information about nimble flashMVC framework, go the flashMVC tab at the top.

Next on my list of features for flashMVC is the application “replayability from imported xml log”. This will be really useful to utilize in Flash or Flex development!

Tags: ,

14Oct Hidden Flash 10 IDE features

While watching the live San Francisco Flash 10 Camp stream over the weekend (ideally I wanted to BE there but Detroit airports where tied up over the weekend), I listened to some points being made that I have heard little or nothing about in its advertised feature roster.

First feature is much better library management. For example when creating new Assets on the stage, you can quickly categorize the asset into a library folder. (small point but every click counts when you work in the IDE all day sometimes)

Second feature is *drumroll* native Flex compiled ActionScript SWCs support! No more nasty hacks to get those libraries working. In addition, this means you can use some of the Flex utility SWCs as long as they do not interface with the core Flex framework. This may mean you can use those utilities like mx.utils.UIDUtil that I had blogged about recently.

Finally there is a new file format coming after the product launches as a plugin (correct me if I’m wrong) that will one day replace the FLA file format. The new data format will then be a simple ZIP format that contains all the library assets seperately and hopefully (unconfirmed) in Flash 11- timeline code will be physical files within the ZIP package that can be versioned seperately allowing better collaboration. Again, this is only a rumar that seemed to be hinted at from the Adobe developers. This would be a huge boon as multiple people working on a FLA nowadays is nightmare.

I also just wanted to mention the Best in Show winner at Flash Camp: www.avenuefighter.com (requires Flash Player 10). This is a very entertaining animation that pulls in twitter posts and builds a scenerio from it that utilitizes the new IK animation system. Congrats team!

Tags:

12Sep flashMVC ASDocs

I just wanted to make a quick update on flashMVC as I have made some further refinements and added ASDocs. Again, please let me know if you have any suggestions or comments!

You can access the docs here: flashMVC ASDocs

Tags: ,

10Sep flashMVC beta released

I have finally released a pet-project of mine for handling simple to complex Flash and Flex applications in a unified way. The framework provides a pattern for MVC (Model View Controller) and has lots of goodies to rapidly build prototypes. In the near future, I will be working on an extension to allow quick unit testing as well as better error handling. This is new so please leave feedback and comments! (-_^)P

flashMVC information and download page

Tags: ,




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