Archive for the ‘Tech’ Category

Crash Course in CouchDB

Monday, August 1st, 2011
CouchDbSince we are considering using CouchDB for data storage on our apps backend (and possibly on the frontend as well) I cooked this small intro.

Some facts about CouchDB that you should know:

  • CouchDB is a JSON document-oriented database written in Erlang.
  • It is a highly concurrent database designed to be easily replicable, horizontally, across numerous devices and be fault tolerant.
  • It is an open source Apache foundation project.
  • It allows applications to store JSON documents via its RESTful interface.
  • It makes use of map/reduce to index and query the database.

Main Benefits of CouchDB

  • JSON Documents – Everything stored in CouchDB boils down to a JSON document.
  • RESTful Interface – From creation to replication to data insertion, every management and data task in CouchDB can be done via HTTP.
  • N-Master Replication – You can make use of an unlimited amount of ‘masters’, making for some very interesting replication topologies.
  • Built for Offline – CouchDB can replicate to devices (like Android phones) that can go offline and handle data sync for you when the device is back online.
  • Replication Filters – You can filter precisely the data you wish to replicate to different nodes.

Taking CouchDB out for a ride

The easiest way to test CouchDB is to use one of the many services on the cloud, I’m assuming for the rest of the document that we use http://www.iriscouch.com, its free (for small users)  and takes seconds to set up.

Feel the Futon

After setting up your account, you should see the Futon control panel in your browser. If not, go to http://mysubdomain.iriscouch.com (that would be the subdomain you just created).
Let’s create a database called mydb.

031

Users in CouchDB

041

Be advised! CouchDB, by default, is completely open, giving every user admin rights. This is great for development but obviously bad for production. In the bottom right, you will see “Welcome to Admin Party! Everyone is admin! Fix this”.
Go ahead and click fix this and give yourself a username and password. This creates an admin account and gives anonymous users access to read and write operations on all the databases, but no configuration privileges.
Users are just JSON documents like everything else so you can store any additional attributes you wish like email for example. You can then use groups within CouchDB to control what documents each user has write access to.

Creating a Document

Now we’re going to create our first document using Futon:

  1. Open the mydb database.
  2. Click “New Document”.
  3. Click “Add Field” to begin adding data to the document. Notice how an ID is completed out for you, you should not change this unless you know exactly what you´re doing (and the chances are that you don’t if you’re reading this). Add key “game” with the value of “Nextive CouchDB Tutorial”.
  4. Make sure you click the green tick next to each attribute to save it.
  5. Click “Save Document”.

05

Updating a Document

CouchDB is an append only database — that means that new updates are appended to the database and do not overwrite the old version. Each new update to a JSON document with a pre-existing ID will add a new revision. This is what the automatically inserted revision key signifies. Follow the steps below to see this in action:

  • Viewing the contents of the mydb database, click the only record visible.
  • Add another attribute with the key “type” and the value “game”.
  • Hit “Save Document”.
After saving, a new revision key should be visible starting with the number 2. Going back a level to the mydb database view, you will still see just one document, this is the latest revision of our game document.
06

Creating a Document Using cURL

I mentioned earlier that CouchDB uses a RESTful interface, let’s prove this by inserting a document using cURL via the Terminal.
First, let’s create a JSON document with the below contents and save it to the desktop calling the file person.json.

{
“name”: “Bruce”,
“surname”:  ”Wayne”,
“type”:     ”person”
}

Next, open the terminal in the Desktop then perform the insert with:
curl -X POST http://mysubdomain.iriscouch.com/mydb  -d @person.json -H “Content-Type: application/json”

CouchDB should have returned a JSON document similar to the one below.

{”ok”:true,”id”:”259191a3020fd260d1bb66cf17594757″,”rev”:”1-f62208cb5761dd5c7d1c5954dfba0e7a”}

This is the ID and revision number of the inserted document.

CouchDB follows the RESTful convention so:

  • POST – creates a new record
  • GET – reads records
  • PUT – updates a record
  • DELETE – deletes a record

Viewing All Documents

We can further verify our insert by viewing all the documents in our mydb database by executing curl -X GET http://mysubdomain.iriscouch.com/mydb/_all_docs

Creating a Map Function

Viewing all documents is nice, but fairly useless in itself. What if we only want to show all game documents?. Follow the steps below to produce the magic:

  • Within Futon, click on the view drop down and select “Temporary View”.
  • This is the map reduce editor within Futon. Copy the code below into the map function.


function (doc) {

if (doc.type === “game” && doc.game) {

emit(doc.game, doc);

}

}

  • Click run and you should see (if you didn’t mess up)  the single game we added previously.
  • Go ahead and make this view permanent by saving it.
071
After creating this simple map function, we can now request this view and see its contents over HTTP using the following command :
curl -X GET http://mysubdomain.iriscouch.com/mydb/_design/games/_view/games
Notice that we get the document’s ID and revision by default.

Reduce Fat Fast

To perform a useful reduce (on SQL we would call this aggregation), add another game to our database and add a users attribute with the value of 5000 to our first game.
08
09

For our new view, we will include a reduce in addition to a map. First, we need to create a map:

function (doc) {
if (doc.type === “game” && doc.users) {
emit(doc.id, doc.users);
}
}

The above map function simply checks to see if the inputted document is a game and that it has users. If these conditions have been met, the game users is emitted. Next, the reduce function:

function (keys, users) {
return sum(users);
}

It takes the users count and returns the sum using one of CouchDB’s built in reduce functions. Make sure you check the reduce option in the top right of the results table as you may otherwise be unable to see the results of the reduce. You need to save the view first to see the results of the reduce.

101

Conclusion

In this article, we took a brief look at CouchDB, one of the more mature NoSQL database available today. Even the most fervent SQL believer can see the advantages that this type of database offers, especially for high demand write operations.


Credits: Luciano Rubinsztejn

UITableView… the Cool Way!

Friday, June 17th, 2011

If you’re working on a UIKit-based iOS App, sooner or later you’ll probably end up using a UITableView.

UITableViews are a really powerful resource when it comes to displaying huge amounts of information. But what happens when you have different kind of cells, with each one of them triggering different actions once tapped?

Yup. You guessed right. The class which implements UITableViewDataSource and UITableViewDelegate protocols ends up being a huge collection of ‘if’ statements… pretty much this way:



- (UITableViewCell*)tableView:(UITableView*)tableView

        cellForRowAtIndexPath:(NSIndexPath*)indexPath 

{

if(indexPath.row == kNameRow) {

  // …

}

else if(indexPath.row == kLastNameRow) {

  // …

}

else if(indexPath.row == kGenderRow) {

  // …

}

else if(indexPath.row == kAgeRow) {

  // …

}

else if(indexPath.row == kPhoneRow) {

  // …

}

else if(indexPath.row == kMailRow) {

  // …

}

else if(indexPath.row == kSkypeIdRow) {

  // …

}

}



This approach has several problems… but the most important one, I dare to say, is maintainability. You’ll probably end up working with a very long method, with different responsibilities. There is a well known correlation between the length of a routine and the number of bugs it might present, due to its complexity.

So… how can you improve this..?

Don’t ask. Just do it!

A nice possibility to lower the complexity of the UITableViewDataSource and UITableViewDelegate would look as follows.

Our solution will rely on two different arrays, containing pointers to the cell providers, and cell ‘press-event’ handlers. Instead of constantly checking which row we’re about to render/ handle, we’ll simply retrieve which selector-should-get-executed for a given row.

Supposing that we want to display two different sections (personal information and contact information), the constructor of our viewController should look this way:



- (id)initWithDefaultNib

{

    if (self = [super initWithNibName:@"NXTableViewsDemo" bundle:nil]) {

_cellProviders = [[NSArray arrayWithObjects:

[NSArray arrayWithObjects:

NSStringFromSelector(@selector(nameCell:)),

NSStringFromSelector(@selector(lastNameCell:)),

NSStringFromSelector(@selector(genderCell:)),

NSStringFromSelector(@selector(ageCell:)),

nil],

[NSArray arrayWithObjects:

NSStringFromSelector(@selector(phoneCell:)),

NSStringFromSelector(@selector(mailCell:)),

NSStringFromSelector(@selector(skypeIdCell:)),

nil] 

  retain];

 

_cellDispatchers = [[NSArray arrayWithObjects:

[NSArray arrayWithObjects:

NSStringFromSelector(@selector(nameCellPressed:)),

NSStringFromSelector(@selector(lastNameCellPressed:)),

NSStringFromSelector(@selector(genderCellPressed:)),

NSStringFromSelector(@selector(ageCellPressed:)),

nil],

[NSArray arrayWithObjects:

NSStringFromSelector(@selector(phoneCellPressed:)),

NSStringFromSelector(@selector(mailCellPressed:)),

NSStringFromSelector(@selector(skypeIdCellPressed:)),

nil] 

retain];

}

assert(self);

return self;

}



UITableViewDataSource Methods

So… basically, instead of having a single provider method, we’re going to have 7 different methods to ‘render’ the cells, and 7 methods to handle the cell events.

Our UITableViewDataSource should look this way:



- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView 

{

    return [_cellProviders count];

}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section 

{

    return [[_cellProviders objectAtIndex:section] count];

}

- (UITableViewCell*)tableView:(UITableView*)tableView

        cellForRowAtIndexPath:(NSIndexPath*)indexPath 

{    

    NSString *provider = [[rowRenderers objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

    SEL providerSelector = NSSelectorFromString(provider);

    UITableViewCell* renderedCell = (UITableViewCell*)[self performSelector:providerSelector

                                                                 withObject:tableView];

    assert(renderedCell);

    return renderedCell;

}



Don’t forget… you need to implement the cell-providers. For instance, the ‘nameCell’ method would look as follows:



- (UITableViewCell*)nameCell:(UITableView*)table

{

static NSString *cellIdentifier = @"NameCell";

    UITableViewCell *cell = [self dequeueReusableCellWithIdentifier:cellIdentifier];

    

if (cell == nil) 

{

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault

                                       reuseIdentifier:cellIdentifier] 

                autorelease];

    }

[[cell textLabel] setText: NSLocalizedString(@"NameCell_Text", nil)];

assert(cell);

return cell;

}



UITableViewDelegate Methods

Finally, the event-handling method should look this way:



(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

{

NSString *handler = [[_cellDispatchers objectAtIndex: indexPath.section] objectAtIndex: indexPath.row];

SEL handlerSelector = NSSelectorFromString(handler);

[self performSelector:handler];

}



Again, don’t forget to implement your event-handling routines, one for each cell.

So… next time you need to enhance your TableView (maybe you need to add another field, or you might need to add new functionality to any of the current cells), all you need to do is add two methods, and wire them up in the tableViewController constructor.

I hope you find this article useful. Have fun!

Author: Jorge Perez

Decomposing Complex Problems into Standard Solutions

Friday, May 20th, 2011

I once worked in a Nintendo DSI game about Tattoos. You had to shop, you had some clients that needed a tattoo, you chose the right tattoo for their personality, and finally you tattooed them.

At some point in development, a Game Designer decided that it would be fun to have some kind of pills that could lower the client’s suffering if you were too sloppy with the needle.

So, we created a button in the game GUI that achieves that effect when pushed.

Easy solution.

With time, this simple requirement grew to be 3 different kinds of pills, 2 different tattoo machines, and a bunch of other weird stuff, all affecting player performance on the tattooing stage.

Furthermore, you could unlock some with progress, you could buy some (and run out of) and I think I even heard something about ‘improving your skill using the item’, but at that point the code was so hardcoded, so patched, so freaking obfuscated, that only the original programmer could touch it.

Our one-button-at-the-GUI solution had mutated into something else… wouldn’t know what to name it exactly…

And of course, we had to reject the ‘improving skill’ idea.

With time, we’ve realized that if we had modeled our solution like a standard RPG-like Item/Inventory system, most of our problems would have never existed, and it would have played nice with how the project evolved.

But this is an easy example - any experienced developer would have seen this coming from far.

Let’s see one a little more complex.

One Complex Problem

The client wanted the troops in our strategy game to move in ‘tactical way’…. meaning that they should use a formation, travel directly to destination, etc.

You could easily solve this by offsetting each about-to-move-unit destination, matching their speed, and calculating a path-finding solution (Dijkstra, A*, or whatever) from the position where they are now to the offset destination. Because they are all probably starting to move from a position near to each other, they are all moving at the same speed, and the final destination is offset to a formation, they will ‘probably’ be able to simulate a formation movement.

This is what old RTSs did. There are even some still doing it now (UFO Afterlight for example).

 

KKND screen capture Separator UFO Afternight screen capture
KKND used a similar approach.
(using just one pathfinding solution, and traveling all units through it)
  UFO Afterlight uses this approach
(but since it is a turn based game, is not a serious problem)

 

Will this work? Well, yes. If the problem is exactly what you initially thought it would be, in this case, just ‘moving in formation through optimal path’, then this solution will work.

But reality teaches us that this is hardly ever the case. Problems tend to evolve, especially if we are working with clients that don’t know what they want.

What if there has to be a specific alignment according to the type of units within the squad?

What if there are lots of wall-like obstacles in the game map, and half our squad ended in the wrong side of the wall while moving near it?

What if, because of the map having many big obstacles (and thus, many curves in the path), the units end up moving like a ‘big ball of soldiers’ instead of the ‘tactical way’ intended? Even worse, this could happen late in the development timeline.

Well… here is where the Hardcoding begins.

Some Standard Solutions

So, is there another way?

Well, instead of just a loop, a path-finding, and a hell of a lot of hardcode, we can decompose the problem into many tinier problems.

Let’s see how the guys on Kaos Studios solved this for one of their biggest games, Company of Heroes.
In Company of Heroes, the infantry is grouped together in squads, therefore the player cannot move individual units. So it’s up to the AI to make them look smart while moving.

To make things simpler they split the squad into three elements: core, left flank, and right flank.

Each element has a leader, and the leader of the core is the leader of the squad.

Each element leader has a number of followers (depending on the side you are fighting on, could be from 1 to 4).

Each follower has a ‘desired’ offset to his leader (’desired’ because some times, the offset may end up inside an obstacle. In that case, the unit will move to the nearest point outside the obstacle).

 

Heerarchical Formation Layout
Hierarchal formation layout.
At the top of the hierarchy is the Squad Leader. Him and each Element Leader is represented by a circle with a star inside. Each one of the leaders may have a number of followers (one in this case), represented by an empty circle.

 

In this way, the formation becomes hierarchal, and the actual problem to solve is much smaller.

When the player issues a move order, the Squad Leader looks for a path to destination. Then, all followers (either an Element Leader following the Squad Leader, or a common Element Follower) will plot a short path to where their leader will be in a near future (let’s say, 2 seconds in the future), offset by their particular offset… and that’s it, with a little speed tweaking, units are moving in formation.

 

Hierarchy predicting where leader would be in the future
Hierarchy predicting where leader would be in the future.

 

With this system, you could cleanly grow to a more complex movement behavior.

In fact, they did, they added path softening so soldiers won’t walk in straight lines, they added some speed variations according to leader distance so they won’t scatter too much and look organic while doing it, they added a limited A* check to see if any of the destinations are on the wrong side of a wall, some alignment adjustment, and many more things.

But in my opinion, the main thing to learn from this experience is that they took a huge, complex problem (Squad Formations), and decomposed it to a few simpler, standard rules (Squad Hierarchy, path softening, steering behaviors, A*), and worked those rules as problems arose.

Conclusions

So, wrapping up, why is the latter approach better?

First, it’s cleaner. We all know clean is the way to go.

It’s easier to evolve from it.

It’s easier to divide the task among a team. This is usually something that is not taken into account when planning a task, but it’s much easier to divide many standard solutions (“Hey, you do the A*, I’ll do the path softening, and someone else the steering behavior!”) than a big ball of hardcode.

And, last but not least, it’s also easier to talk with other team members (for example, a Game Designer or a QA) about something like an RPG-like inventory system, rather than “an array that holds the items the player can use”. In a team we are not all programmers, but surely we are at some degree, gamers.

In a goal-orientated industry, it’s difficult to have time to plan ahead for solutions; we all know there is never enough time. But it is important to understand that maybe not every time, maybe not in every task, but identifying and planning ahead the main problems of a project not only boosts quality, but in the late development timeline, it saves time. Decomposing complex problems into simpler-standard solutions is just a technique to do so.

 

Author: Martín Moreno
Sources: AI Game Programming Wisdom 4 – Company of Heroes Squad Formations Explained, Chris Jurney.

ANTs work for you

Friday, April 29th, 2011

Do you want to step back and watch your most complex Flash build process be successfully completed with the press of a button? Then you should try Apache Ant.

Ant is a command line tool that makes your life easy by automating build and deploy processes with a build file. The only thing you need is to have Apache Ant installed, the Flex SDK, an XML file and a simple command-line command: ant.

Lets start with a simple build file (for mac, for windows you may have to change the paths):




<?xml version=”1.0″ encoding=”UTF-8″?>

<!– The ${basedir} value of this project is the directory in which this build file is placed. –>
<project name=”build” default=”compile” basedir=”.”>

<!– This creates a property called FLEX_HOME that can be accessed with ${FLEX_HOME} –>
<property name=”FLEX_HOME” value=”/Applications/Adobe Flash Builder 4/sdks/4.1.0″/>

<!– imports the Flex Ant Tasks from the flexTasks.jar that comes with the Flex SDK –>
<taskdef resource=”flexTasks.tasks” classpath=”${FLEX_HOME}/ant/lib/flexTasks.jar”/>

<!– This is the default target that gets executed when using this build file. It compiles the app using the mxmlc task from the Flex Ant Tasks –>
<target name=”compile”>

<!– This is the actual call to the task used to compile using mxmlc –>
<mxmlc file=”${basedir}/Main.as” output=”${basedir}/bin/Main.swf”>
<load-config
filename=”${FLEX_HOME}/frameworks/flex-config.xml”/>
<source-path
path-element=”${FLEX_HOME}/frameworks”/>

</mxmlc>
</target>
</project>



This build file will compile a Main.swf file in the bin directory using the classes from the basedir directory (in this case it
s the directory in which this build file is located). Copy the XML to a text editor and save it as build.xml. Please dont forget to change the value of the FLEX_HOME property to the location the Flex SDK in your system.


In order to test this build file you
ll first need to install ant:

For mac you can follow the instructions of this great post:
http://www.asceticmonk.com/blog/?p=388

For windows you can use this other one:
http://blogs.sun.com/rajeshthekkadath/entry/installing_ant_on_windows


Now that you have Ant installed lets create a project for the build file and we need to call ant to compile the Main.swf file:

  1. Create a new folder anywhere in your system and put the build.xml file in it.
  2. Next to the build.xml file create an ActionScript file called Main.as.
  3. Open a Terminal and navigate to the project folder.
  4. Type ant (and press enter) and wait for a few seconds.
  5. Thats it! You compiled using Ant! You should see the Main.swf in the bin folder.

Ant can create, delete and move folders and files. It can also execute pretty much anything that can be called using the command-line. There are also plugins that can be used with FlashBuilder or FlashDevelop that help you call the ant scripts or different parts of them with simple clicks.

A separate file called build.properties is usually used to configure all the paths and file names that the build.xml needs to work. In our example, the Flex SDK path, the name of the src file (Main.as) and the name of the output file (Main.swf) would be in that configuration file. This way the build.xml file only has the logic and the build.properties file has all the configurable elements.

Heres an example of a build.properties file:

# change this to your Flex SDK directory path
FLEX_HOME = /Applications/Adobe Flash Builder 4/sdks/4.1.0

# main file name and path
MAIN_CLASS = Main.as

# output file name
OUTPUT_FILE = Main.swf


It is also considered a good practice to copy the flexTasks.jar to the lib folder instead of using it directly from the Flex SDK. This way the file can be committed to an svn with the rest of the files of the project.

At the end of this post theres an example project available for download that uses the build.properties configuration file and multiple tasks to compile, create a swc and and create an html wrapper.

I hope this helps you get started. You should now have all the bases you need to get deeper into Ant. I think youll love the power of the one click/key automation!


Sample Ant project
: Thanks to Santiago Puente.


For more information about Ant and the FlexTasks:

http://livedocs.adobe.com/flex/3/html/help.html?content=anttasks_1.html

http://www.allapplabs.com/ant/ant_basics.htm

http://wiki.apache.org/ant/AntTasks

Welcome Android In-App Billing

Monday, April 18th, 2011

One of the key monetization benefits of the iOS platform comes to Android: in-app billing. This new platform capability allows app developers to have free apps and monetize via virtual goods, a feature vastly used in top grossing iOS apps. Android is now pairing up to iOS in its several monetization alternatives: paid apps, in-app billing and advertising.

Below a chart of the in-app billing architecture (also here http://developer.android.com/guide/market/billing/billing_overview.html)

Architecture

Note Android’s in-app billing offers server-based content delivery, similar to iOS, and more secure than bundling content within the .apk file. More security and design guidelines at: http://developer.android.com/guide/market/billing/billing_best_practices.html

Developers need to have a Google Checkout Merchant account and there is a sample application in Android’s SDK that helps demo an implementation of in-app billing.