Search Flex Components Free

Custom Search

December 10, 2007

API's with Delimited ASCII text vs XML or AMF

have been working on a card game for AIR and just finished the API for the game. The API returns shuffled decks of cards with some parameters in the URL. In looking at the various formats, I chose delimited ASCII text. The question you are asking is why, well sometimes XML and AMF are overkill and honestly delimited ASCII text is fast to parse and easy to use/debug. On the client side in Flash Player, String.spilt is over 10x faster than both XML and XMLDocument in parsing speed and is linear in performance with size of the text being parsed. If you are simply passing an array of strings, you might want to look at using delimited text. It isn't glamorous but it works and is easily scalable on the server side with caching and compressed if your server supports gzip.

So here are the API details on the Card Shuffle API:

// Default URL
// 1 is the version # of the API

// Decks Parameter - Shuffle 3 decks of 52 cards each

// Jokers Parameter - Shuffle 2 decks of 52 and add in 2 jokers per deck

The logic shuffles an array of cards randomly between 5-20 times and each shuffle uses a new random seed value. This makes it easy to build the game logic client side without having to worry about shuffle randomness and allows for multi-user. More on the multi-user behavior in a later post.

In Flex 3 I wrote a simple API Test client that shows the decks visually. The card graphics are loaded from a Flash CS3 SWF9 file dynamically (more on the technique here) so that I can swap the card designs at runtime as a user preference. So here is the example with full source:
Card Shuffle API Tester in Flex 3
Card Shuffle API Tester in Flex 3 Source

I used a simple HTTPService tag like so:

result="shuffleServiceResult( String( event.result ).split('|') )"
url="{'' + decks.value + '/' + jokers.value}"

Note that the resultFormat is set to 'text' and when the result event is fired I used String.split to parse the result into an Array. I used the "|" as the delimiter. If you look at the raw text results you will see a number in the first array position, this is milliseconds from 1/1/1970 (Epoch) and makes it easy to transform into a Date object via the constructor like so:

// shift a value off the array, turn it into a number and pass it to the Date constructor
shuffleTime = new Date( Number( data.shift() ) );

Basically this simple API allows me to get shuffled decks of cards for my upcoming AIR game. I will be posting more about the making of as things progress.

Related Flex Tutorials