Geenat.com Nathan’s blog about software development, design and the people behind it.

Video Game State Machines, The Easy Way!

Written on April 2nd, 2011

First, what’s a State Machine?

State Machines are used in everything from video games to applications to embedded systems such as control stations. In the case of video games, they can be used for actor logic, basic artificial intelligence, screen management, level management, or anything else in need of organized state-driven logic.

If you’re a newcomer to state machines, they may sound complex, but in reality are fairly simple and easy to implement in code.

What does a State Machine look like?

The example pseudo-code below is written with C in mind, but the concepts are directly translatable to most other languages including Java, Python, and Flash/Actionscript.

State Machine using traditional switch/case in C:

enum
{
    STATE_IDLE = 0,
    STATE_RUN,
    STATE_JUMP,
    STATE_DEAD
}

int state = STATE_IDLE;

void StateUpdate()
{
    switch(state)
    {
        case STATE_RUN:
            printf("Run logic.");
        break;
        case STATE_JUMP:
            printf("Jump logic.");
        break;
        case STATE_DEAD:
            printf("Dead logic.");
        break;
    }
}

void Update()
{
    // Change the state.
    state = STATE_RUN;

    // Run the current state.
    StateUpdate();
}

As illustrated above, the most common and obvious way to implement a State Machine is through the use of a variable to hold the current state, a number of pre-defined constants to represent different states, and a structure of control statements such as switch/case to perform logic based on the current state.

Looks simple, right? How could we improve on this?

Function pointers can make extremely simple State Machines that work without any extra constants or conditional statements. Function pointers are built into most languages in one form or another. Consider the following:

State Machine using a function pointer in C:

void (*StateUpdate)();

StateUpdate = NULL;

void StateRun()
{
    printf("Run logic.");
}

void StateJump()
{
    printf("Jump logic.");
}

void StateDead()
{
    printf("Dead logic.");
}

void Update()
{
    // Change the state.
    StateUpdate = StateRun;

    // Run the current state.
    StateUpdate();
}

Easy. These are of course very simple examples; in a real video game you’re likely to have initialization states and multiple State Machines running alongside each other.

Since writing this article, I’ve had a number of people ask me how to implement the above example in a language other than C. Below I will illustrate how one could implement the same State Machine in a higher level language such as Python. In Python, functions are first class datatypes, which means you can re-assign them like variables. No function pointers needed!

State Machine using first class functions in Python:

def StateUpdate():
	pass

def StateRun():
	print "Run logic."

def StateJump():
	print "Jump logic."

def StateDead():
	print "Dead logic."

def Update():
	StateUpdate = StateRun
	StateUpdate()

What can I say, Python rocks!

Posted in C, Game Development, Programming, Python

Programming Musical Tastes. What do you listen to while you Code?

Written on May 3rd, 2009

cat-retroMost of the people reading this blog will probably agree that programming is one of the most mentally engrossing tasks out there. I believe this certainly has an effect on the variety of music listened to by people who write code.

Michal Marcinkowski, the creator of the infamous popular online action shooter called Soldat, is a huge fan of programming to heavy metal music. Michal listens to metal bands such as Manowar, Amon Amarth and Moonspell. He compares listening to metal as absorbing pure energy, using that energy in his programming efforts.

On the other hand, Dan “Data” Tabar, the main guy behind Data Realms, tends to listen to softer music such as chiptunes (including demo scene music) and retro video game music while programming his game, Cortex Command.

Personally, and surprisingly enough, I am partial to silence when programming. I’ve done some of my best programming and deepest thinking with a pair of earplugs. Although I do admit, some music is great to keep the thought process flowing; and in this case, my musical choice varies depending on what I’m working on. If the ideas I am translating into code are fairly complex, I will listen to something non-lyrical. This includes classical music such as Beethoven or Mozart, electronica, or similar to Dan, even tunes from retro video games.

Here are some sites that stream music I enjoy programming to:

http://www.kohina.com/ – Old school game and demo scene music.
http://www.di.fm/ – Electronica, classical and much more.
http://www.micromusic.net/ – Low tech music for high tech people!
http://www.scenemusic.eu/ – Demo scene music.
http://www.shoutcast.com/ – Good for everything else you can think of.

What do you listen to while you code? Feel free to share your musical recommendations and add your thoughts below!

Posted in Game Development, Programming

Carrier has Arrived!

Written on October 8th, 2008

I would like to dedicate a post to my computer scientist friend, Josh Carrier. It was his Birthday yesterday; happy birthday Josh!

His brand new blog over at javadocs.wordpress.com is fantastic; it details his work on many interesting and geeky subjects, including but not limited to: Robots, Linux, Artificial Intelligence and of course, Java. I wouldn’t be surprised to see Josh complete a skynet equivalent in the future (..without the apocalyptic tendencies, of course).

Speaking of Java; Josh is quite obsessive about Java. As a computer language guy myself, I find this to be a good thing (what can I say, Java is awesome). Josh uses Java for many of his projects, one of which included solving a complex tetris cube using the awesome power of distributed computing.

The distributed computing project was born one evening after Josh and his roommate purchased one of the tetris cubes and attempted to solve it by hand. The tetris cube puzzle itself is quite complex; before you even crack open the package, it challenges you with a slogan like “9,839 solutions, we dare you to find one!”.

After many days of trying to solve the cube, Josh became inspired to build a distributed computing system to help. He went on to build a solving client, and a central server (which worked with the clients, collecting stats and managing workloads). Running these clients on any processing power he could spare, he also enlisted the help of a number of his willing colleagues, myself included.

Leveraging my new dual-core, I joined “the collective” (as Josh liked to call it). A number of days, and a few billion iterations later, the group of about a dozen computers, using Josh’s software, solved the tetris cube. Interestingly enough, it was my own AMD Athlon 64 X2 5000+ (absolutely shameless plug for AMD) which ended up finding the first solution to the puzzle. It was certainly a fun project to be involved with.

Congratulations to Josh on his new blog; I find it excellent how our humble network of geek blogs is gaining more momentum every day.

Posted in Java, People, Programming

Dina Programming Font in TTF format

Written on October 7th, 2008

For a long time now, Dina has been my favorite programming font. I find it crisp, clean and very readable for the amount of pixel space it takes up (wide bowls, no unnecessary serifs). It’s certainly a nice change from Courier New. In my opinion, a great programming font is just as important as any other tool in the programmers toolbox.

Unfortunately, Dina does have one big pitfall. It’s only available in the bitmap based .fon format, which is notorious for bad portability. Incompatible on anything but Windows, and even some Windows applications will not read this format (Sun’s Java Netbeans IDE for example does not support it).

After a long day of various hacks and adjustments, I was able to convert the Dina font to a working TTF format. You can now benefit from the fruits of my labor using the link below:

Dina truetype font pack

Here is a preview for your viewing pleasure:

For those interested, this is a screenshot from the Netbeans IDE. I have been recently giving Netbeans and Eclipse a test drive in preparation for my upcoming developments in Java.

Posted in Download, Programming, Typography