Jul 9 2010

Building a Game

A lot of my peers went to school to become game developers. Instead, most went on to work for big software companies in northern Virginia. I studied human-computer interaction and wanted to fix everything from poorly designed user interfaces to frustratingly complex household items. Instead, I became a Mac, iPhone, Flash and game developer. In a way, we both went where the money was.

How to start your game

I’ll assume you already have a game idea. No matter how ambitious you want to be though, think in milestones

  1. Display some graphics.
  2. Animate your graphics, either manually, or with basic input controls
  3. Get hit detection working.
  4. Everything else! (level loading, artificial intelligence, etc.)

If you can even make it to the fourth milestone, you’re farther than 90% of most game developers. If you make it past milestone four, you’re farther than 99% of game developers. Only the passionate, motivated and able ship. This is how I’ve started all of my games and it’s important to achieve tangible results to keep yourself motivated. In fact, this same step-by-step process can be used in regular application development as well.

Design

Start your development with a skeleton application. This does one of two things: first, it forces you to plan the architecture of your application by creating the objects (in files) that you’ll need in your development and second, it provides an outline for you to work from. So first, think about what display controllers and object controllers you’ll need, what model objects you’ll need and then go ahead and create the files for those. Also go ahead and fill in some functions too for the basic functionality. The point is, make sure you break up the functionality into bite size chunks. It’ll make your life easier, trust me.

Put in the functions you think you’ll want and then just put in print or trace statements to make sure they’re being called correctly. Then, just build it piece by piece, usually starting with getting something like a player character on the screen (DisplayController, PlayerController, GameController), then getting him to move, moving him via inputs (InputController), then applying constraints like hit detection or getting him to jump (implementing basic gravity), etc, etc. Just keep introducing and implementing new features, one at a time, playing the game, realizing you want to tweak something and playing it some more. This is called iterative design.

Get those milestones done as quickly as possible, keeping your code organized in your skeleton application. Don’t worry about graphics at first. Personally, I stick in multi-colored boxes instead spending a lot of time on graphics I may not use in the end. Objects will be added as you realize you need them, but the idea is to keep it organized, simple and cohesive.

When designing your class structures and diagrams, keep the low level functionality, like file access and keyboard inputs, abstracted and hidden in wrapper classes. The reason you abstract objects is for a couple of reasons: One is to be able to add in hooks before and after a part of code. For example, instead of calling the system clock directly, you want to calculate the elapsed time if your game was paused or suspended on the computer. If you abstracted this in the beginning with a GameClock object, you’d only have to change it once, in a single place. If you called it directly, you’d have to go back to every place in your code and calculate that value. Keep object responsibilities where they belong!

Start Programming!

To start you off, check out a game template designed for the Corona SDK (free 30 day trial), written in Lua. I recommend you create a template of all your project tyes as it’ll help jump start your next big idea and also keep you organized from the start.


Jul 1 2010

Why Your Code Sucks – Naming Conventions

I’ve seen a lot of poorly written and ugly looking code in my time. That’s not even considering the undocumented and uncommented code. We all know we should comment our code but how many of us do it consistently? I admit, when I’m in a coding frenzy, stopping to write comments just gets in the way of my thought process and can be distracting. I will however write a bunch of comments before I write the code, of the operations I think I need, in order to give me an outline of where I need to get to. For example:

// Get URL string for video file
// Load video file from URL request
// Load video file into video player
// Set up video player
// Play video

I may not know all the APIs to load and play the video just yet, but at least I’ve given myself an outline and as I fill in the code below each comment, I can see exactly what I’m doing and where I need to go.

Why Your Code Sucks

The point of this article is not to talk about comments, but how to avoid writing them in the first place within your functions and still be clear for everyone else, for the most part. This is your code:

newPlPt = crt2pl( nmc.x, nmc.y );

Not even a comment could concisely convey the meaning of that hideous statement. Instead, why not:

newPolarPoint = cartesianToPolar( newMediaContext.x, newMediaContext.y );

Well written code is self documenting. Let me restate that: if you can write code so that someone can jump to any point of that code and understand what’s going on at that point, read it like a sentence, and not have to decipher minute details like what each variable means, then you don’t have to comment most of your code.

There’s no reason you need to shorten the names in your code. Most programmers have never had file size limitations to deal with, so there’s no reason for it. Stop pretending you live in the 1960s and embrace nearly infinite file storage. To save keystrokes perhaps? Please, use a real IDE with code completion and stop doing stupid things like:

public function updateP( p:Player, d:MovieClip, b:MovieClip, t:Textfield);

Function Names

Also, because your functions are essentially actions, they need to reflect that in the name, so put a verb in the beginning of your function such as: getData(), setStatus(), enableWiFi(), hideControls(), handleGraphicException(), launchBall(), etc.

Class Variables

Get rid of the underscores in front of your class variables. For example: _dg; _myNumber;. All class variables should be private anyway, so why do you need that ridiculous convention? It’s a hold over from C where there was no “private” keyword, so you’re using it and you have no idea why.

Also, what’s with the “my” naming convention? You sound stupid when you have those: myInstanceName, myMovieClip, myGraphicsContext. Of course it’s yours, whose would it be, if not yours? If you’re programming with a colleague, do you refer to his variable references as yourInstanceName? Or hisVideoFileURL? Of course not. Don’t be that stupid; you’re reading too many stupid online tutorials by uncreative people who only code because they have nothing else better to do while living in their parent’s basement.

In the very least, be consistent with your naming conventions.

Hungarian vs. Polish notation

Depending on which language you’re coding in,  you may need to use a notation to help you with type casting. Let me rephrase that: if you’re using a loosely typed language, use Hungarian notation. You should probably use this with strongly typed languages anyway because with abstract types, you never know what you could get into and it’s just generally less confusing.

Hungarian Notation: vendorNameTextField or vendorName_txt

Polish Notation: txtVendorName or textFieldVendorName

Why not Polish notation? Not only is it ugly, but why would I sort on variable type instead of the variable name like I can do in Hungarian notation? The notation names come from how the speakers of those languages modify their verbs and nouns. To say: “My ball” in Hungarian is:  ”labám” where “labda” is the root word and the ‘m’ singifies a first person possessive. Hence the ending of the word shows the crucial information. It’s the opposite in Polish notation where the beginning of the word is modified. In the interest of full disclosure, I love the Polish, but I am Hungarian, but I promise that’s not why I prefer one over the other.

Final Thoughts

In the end, be consistent, be clear and spell out your variable and function names.


Jun 27 2010

Corona Game Template in Lua

This is a template I threw together for the Corona SDK from Ansca Mobile. Since Lua is not a language most people are familiar with, I figured I’d throw together some sample code for Corona and share what I learned so far with the rest of the Corona SDK community by including the template here.

The template includes example code for:

  • Display groups
  • Orientation and accelerometer
  • Touch with buttons
  • File reading
  • Example level file for scripting game play

The template separates functionality into modules for an object oriented approach. I’m still learning the techniques for Lua, so if you notice a better way to do it, please don’t hesitate to let me know in the comments below. Some things in the template are not the best way to accomplish some things, but should give people a good idea on best practices of software design. This will also with work Corona’s Game Edition.

If you find the template useful, please consider buying a copy of our current application to support us. It’d mean a lot. Also, check out our company website if you’re an iPhone programmer as we’re looking to bring on some independent programmers.

Download the Template Code

Again, if this helps you out and you want to support us, check out the links on the side. Thanks!


Apr 14 2010

BarNinja – An iPhone App Postmortem

The BarNinja iPhone app is a mixed drink application with over 730 drink recipes with additional features including a random drink selector, bartending tips, powerful search, and a shots per bottle calculator for party planning.

The Beginning

As far as we could tell when we started the BarNinja iPhone app, there weren’t any other apps like it on the Apple App Store. That was back in April of 2009. While I was in San Francisco back in March, I got a Facebook message from Jason asking if I was interested in doing an iPhone app. I had done a bunch of Mac development and even independently sold a previous application. I had also attended Apple’s developer conference (WWDC) on two separate occasions so I was quite comfortable with developing for Apple products. When I got back from California, we sat down at a local bar in Blacksburg and wrote down our ideas for the app he wanted to make. That was prior to iPhone OS 3.0 being released and we were counting on some key features in that release for our app. In the end, we ultimately failed when the features didn’t work out exactly as we expected. Luckily, only a little code had been written and that was enough to get me up to speed with the current iPhone development platform.

Instead of quitting, we got BarNinja, another local Blacksburg startup involved in another app idea. We wanted to leverage the shake feature (iPhones can detect when you shake them) that was relatively new and make a mixed drink app based around that.

Soon after we started, a few other apps starting hitting the app store with exactly those features. But the competition didn’t deter us, but instead pushed the bar higher for us. We now knew we couldn’t just make another mixed drink app with a shaker feature, we had to make the best mixed drink app with a shaker feature. We were also creating a 730+ recipe database (including ingredients and other drink information) that would hopefully give us an added advantage. Luckily, at the last WWDC (2005) that I attended, they announced a technology called CoreData which allows developers to place small databases easily within their applications. They also included it in the iPhone OS and I ran with it.

Problems and Solutions

The problem with having 730+ recipes is that it becomes nearly impossible to find a drink in a list. The list view we had, took minutes to scroll through and even tired out your finger having to swipe so much! We added an index on the side to quickly scroll through the list alphabetically. We also added a search to find a drink by name and even added a filter to sort out if the drink was a “mixed drink” or a “shooter.” But that still wasn’t good enough.

I could find drinks like “Vodka Martini,” but what if I wanted a drink with vodka as an ingredient? So we added in a search that would find ingredients too. That worked out well, but often times vodka isn’t named vodka, it’s also names just “Absolut,” which everyone knows is vodka, but the iPhone doesn’t, so we had to teach it what kind of alcohol those products were.

More progress, and we were rolling right along until we tested it out on the actual device; it was painfully slow. The user would hit a key on the virtual iPhone keyboard and the key would get stuck in the “up” position until the search was done and only then could you hit the next key. Searching 730+ recipes is easy, but searching on average 6 ingredients for 730+ (~730 x 6 = a lot) takes 4 or 5 seconds on an iPod Touch 2nd generation. So we had to get a little creative.

My solution was to split off the search into a separate thread (a simultaneous process within the application) and perform the search in the background. This introduced a few other problems that I had to fix but the responsiveness improved dramatically. Then, using Apple’s performance tools, increased the search algorithm by about seven times. Thanks to all those boring Computer Science classes I took at Virginia Tech I was able to speed it up and also make it appear to speed up.

Updating the table view, after finding each recipe that matches the criteria, is slow (thanks to the performance tools for reminding me of this). So I returned the first 5 results instantly because those are the only ones you can see initially on the screen and then the rest were updated in a decaying frequency as they were found until the search was done.

Iteration

Early Search

Early Search

Icons, glass name and index

Icons, glass name and index

Early drink details view

Early drink details view

The Final Product

Initial Screen

Initial Screen

New search screen

New search screen

New drink details view

New drink details view

Results

They say if you’re happy with your 1.0 version of your application, you didn’t release it early enough. While we definitely have plenty of work yet to do on this application, we didn’t release it soon enough. It did not take a year of programming to get this done. The programming was the easy part, it was all the other stuff that got in the way, distracted me and things I had to wait on that took the longest. Back in the day, when doing my Computer Science homework, the motto was “Start early, and start often.” That rings true for every long term task.

We didn’t run any real usability tests. This upsets me a bit, but we never really got to show it to too many people. Now LTZ has a few more developers working on more apps, so we have a larger pool of testers, but in the end, we still need to test it out on real human beings and put all those Human Computer Interaction (HCI) skills I spent a lot of time learning, to use.

I did try to apply those skills with the layout of the app. When the app launches, the first screen is the random drink screen, which you can tailor to your tastes in the options. We wanted to give the person using our app something to do right away. We didn’t want to over whelm them with a list of 730+ ingredients; it doesn’t impress anyone. In our limited testing everyone figured it out and got a kick out of the shake feature. With other apps, we noticed, they presented a huge list of options that just left you wondering what you should do next. It’s that classic “uuuuh” moment. With ours, right after the launch of the app you can start enjoying the functionality.

The next screen is the raw list of drinks, plain and simple. Our search is straight forward and easy to figure out and the index on the right helps users navigate down the list quickly. We also stuck to using as many user interface elements from the standard set of Apple iPhone as possible. Many other apps try to be creative and diverge from the standard set of UI elements and consequently from the Human Interface Guidelines that Apple has set forth. The result is a poorly designed, clunky looking application that takes time to figure out how to use. Since we’re using a standard search bar, people using our app know right away what that means and can start right away in using the search feature.

We also chose a dark theme for our colors, not because it looks cool, but because most of our users, we assume, will be using it in a bar, or bar like conditions such as a party, etc. But we also didn’t want to give it a depressing theme since it was suppose to be fun and helpful, so there are a few bright colors in there. The design will most likely change and be updated, but that’s the rationale for the initial release. We’ll see what our users think and how they use the app.

We know our app isn’t perfect, but we’re confident we know where to go from here to improve it and fix some of the problems we know exist in it. Through additional usability testing, we’ll slowly improve upon BarNinja to make it the best drink application on the app store. We know we’re not there yet with the initial release, but we look forward to adding great functionality that people will love.


Jan 27 2010

Handling Your Initial View Controllers for iPhone

Programming starts with a

design

A lot of webpages and articles talk about how to program, but they don’t talk about how to design a program. Good program design separates the weekend programmers from the professionals. Sure, anyone can piece together a working application but a good design allows a power and flexibility of adding new features, for example, without having to recode half of your application.

Here, we’ll talk about handling your initial views when your iPhone application loads. This might be a simple task if your application is simple, but take the case of having a welcome screen followed by a login screen followed by a tabbed view controller. You might set it up so that one activates the other upon being dismissed itself.

Here’s an example of how the process might look:

Program loads AppDelegate

Load Welcome view from AppDelegate

Dismiss Welcome view -> Tell Welcome view to load Login view

Dismiss Login view -> Tell Login view to load Tabbed view

What if you had to add a view or remove one, say if the login was no longer needed if you gave your users the option to save their credentials. You’d have to rewrite two different view controllers at least. And this is just a simple example so you can see how complicated this chain of views would get once your application grows. For most programmers this way is fine, and sadly enough most of the time, this is the way it’s done. But true programmers are lazy. Lazy programmers are good programmers. So be lazy and write good code so that when (not if) you go back and edit your code, it’ll be a snap.

A design starts on paper

Your programs should be conceived on paper. Even with applications that attempt to do this, I still find paper the ultimate programming tool (even though I did the one below on a computer).

Class Diagram

Class Diagram

First off, your controllers should be logically separated based on their tasks that they need to accomplish (not based on how the user will view them). So, you should have a controller or controllers to handle logging in and session creation and have appropriate UIViews and UIViewControllers to get and display info to your user. This may not be a one-to-one relationship though. For example, you may not have a UIViewController that’s associated with creating your sessions at all.

Next you will have your application’s business logic view controllers, controllers and all that jazz. The controllers sit independently to the view controllers except, of course, where there’s coupling or interaction. They are not tied directly, or rely upon any particular view. You illustrate those connections on paper (or in this case in the example diagram above). So if your “Add New Event” feature, let’s say, needs access to the session data, draw a line from your SessionController to your EventsController with an arrow pointing in the direction of the flow (from EventsController to SessionController in our case since the Events controller needs to know about the SessionController but not vise versa).

Abstraction solves everything

Since your controller code should be independent of how your views are laid out, you won’t have your AddNewEventViewController (the view that lets the user add an event) handling the actual creation and saving of events but will instead gathering and packaging the information taken from the user and given to an EventsController to handle the manipulation. Who knows, you may have several views that edit an Event in one way or another and if you change something in how the Event is saved, you’ll have to go into the code of each one that touches Event and rewrite code — exactly what we’re trying to avoid.

Abstracting the data in this way is called indirection and “All problems in computer science can be solved by another level of indirection;” — David Wheeler, except as Kevlin Henney says, “…except for the problem of too many layers of indirection.”

Singletons, under used

and under appreciated

So, you should have a session controller that sits somewhere ready to be called by who ever needs to validate a session or login (those views that would need access could be your tabbed views, could be your app delegate when your app starts, or could be in your settings views where you type your login info or when you log out). This is usually accomplished with a singleton class where any controller can access that one (and only) instance of your controller without having to pass around references to that controller. It not only cleans up your code, but also helps data integrity by not allowing multiple objects to edit the same data.

Handling your initial views

You should really have a separate controller handle organizing your views rather than the app delegate since the app delegate should really only be used to initialize your app and handle delegation of your application, not controlling business logic. So the structure should look like:

AppDelegate -> MainViewController -> LoginViewController

I like to have an overall MainViewController that handles all the subviews, be it a tab bar view controller, a table view controller, or whatever your main view is going to be. This level of indirection allows you to easily change what your main view controller is later, should your requirements or ideas change. Having said that, the MainViewController is going to need to get and maintain a reference to the application’s window.

To actually add the views, stack them on top of each other. Add the Tab Bar Controller’s view to the Window’s view first, then if needed, add your login views after that to stack them on top, and then remove them as needed when you’re done with them. By removing them from the top, it reveals the bottom view.

In MainViewController’s implementation file, your viewDidLoad: will look like:

- (void)viewDidLoad
{
[super viewDidLoad];
[mainWindow addSubview: tabBarController.view];
[mainWindow addSubview: loginViewController.view];
[mainWindow addSubview: welcomeViewController.view];
}

Where mainWindow is an IBOutlet to your Window in your MainWindow.xib file (or you could get it programatically if you prefer). Also, loginViewController is a pointer to your view controller that you put on top of the tab bar controller. On top of your login view, put a welcome view displaying any text, graphics or video to show after your application loads; note that this is different from your Default.png initial image. Then when you’re done with your login view, call removeFromSuperview on them to remove them from the view stack. So something like this in your MainViewController (since it handles all manipulation of your main views):

- (void)removeWelcomeView
{
[welcomeViewController.view removeFromSuperview];
// Any other code you need to clean up after your welcome view is removed
}
- (void)removeLoginView
{
[loginViewController.view removeFromSuperview];
// Any other code you need to clean up after your login view is removed
}

Obviously, when you remove the welcome screen view, under it (since you added it on the stack before the welcome view) is your login view. Then, removing the login view will show the tab bar view since that was added first in your view stack:

(Top)

Welcome View

Login View

Tab Bar View

This way we’re loading all of our views at once and stacking them so the one on top hides the one below. This has a slight overhead since you’re adding all your views when your applications starts but you can always delay adding the tab bar controller to the Window’s view until all the initial views are removed, for example. Then, if you’d like, using the MainViewController, you can add views on top of the tab bar view during execution, for example if you need to login again.

There are a few different ways to handle multiple views and each case is different. This is just one idea, with a few general guidelines. Feel free to ask any questions in the comments if anything wasn’t clear enough.

Sample Code

The following sample code is provided as is for educational and demonstration purposes. I threw it together really quickly and is only used to demonstrate the use of a MainViewController. Normally, you’ll want to make your MainViewController a singleton class, but in this example I passed the MainViewController instance to the subviews in order for them to call different methods on MainViewController to change the current views. By using a singleton design, you can avoid passing around this reference since there is only ever one MainViewController.

Also, this code demonstrates how to create a tab bar programmatically. It needs to be the root view of your window, but that doesn’t mean it needs to be the root view controller. We are still allowed to use a MainViewController as our root to handle all subviews and their controllers.

Download sample code (2010-02-11_TabBarTest.zip)