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

Why you should use PNG for web design, and how to do it properly!

Written on July 9th, 2009

PNG SamplePNG is a fantastic open source image format that has the technical potential to be the do-all end-all for graphics on the web. In theory, PNG has a sizable list of advantages for people designing websites, including:

  • Full color support.
  • Full alpha channel support. (In modern browsers above Internet Explorer 6)
  • Efficient lossless compression. (And by the end of this article, smaller than an equivalent GIF!)
  • Patent free and open source.

However, in practice one will notice that some web browsers have mixed support for certain features found in the PNG format (usually PNG’s built-in gamma and color correction aka color profiles. Which can inadvertently cause serious differences in shade and color when viewing the same PNG image on different browsers). These inconsistencies cause a huge headache for web designers who wish to use this format for images in their designs!

That said, in this article I will show you how to solve this issue so that your PNG images display flawlessly on all modern browsers! This method also has the welcome side effect of shrinking the PNG file size, making them smaller than an equivalent GIF, and sometimes even comparable to the size of a lossy JPEG!

This process of “PNG Optimization” is extremely easy when one has the right tools. Luckily enough, Windows, Mac and Linux users have a fantastic open source utility called pngcrush. Since it’s a command line tool, you can optimize a virtually limitless number of .png’s with a single command! Perfect for processing the “/image” directory of a website.

pngcrush -rem alla -d outputdir *.png

For those wondering, “-rem alla” stands for “remove all ancillary chunks”.

This command strips out all ICC color profiles, gamma profiles, and other unnecessary auxiliary data that is generally used in photography, but not needed in website design; effectively solving consistency problems between browsers. In addition, this extra data can use up a lot of space in the PNG image, and once it’s stripped out the size of the PNG will generally shrink down significantly.

pngcrush sample image

For Windows users, I’ve created a simple batch file that will run this command for you with a click of the mouse. Just remember to place the batch file, pngcrush.exe and the images to be optimized in the same directory before running it.

You can download the batch file, including the Windows excecutable of pngcrush from me directly, or get the latest version of pngcrush at Sourceforge.net

Enjoy! And I hope to see more usage of this great image format on the web.

Additional Resources:

TweakPNG – A utility for exploring the internals of a PNG file. For anyone who wants to see exactly what is inside of their PNG files. (http://entropymine.com/jason/tweakpng/)

Posted in Download, How To Guide, Open Source

Microsoft has been caught installing exploits into Firefox through Windows Update!

Written on June 9th, 2009

As part of their monthly set of security fixes to Windows, Microsoft has decided to make modifications to the Firefox web browser. The modification is an extension called Microsoft .NET Framework Assistant, featuring Microsoft’s “ClickOnce technology” which enables any website to easily and quietly install software onto the host computer.

Microsoft has literally modified Firefox without our knowledge or permission with the effect of adding a significant back door for malicious software creators.

Now the whole reason I use Firefox is because I do not want websites to have the ability to easily and quietly install software that could potentially mess up or take over my system. As mentioned in my previous post, this is the primary reason why I left Internet Explorer in the first place.

I personally think this is absolutely appalling and sheds even more light on Microsoft’s disgusting, anti-competitive business practices. These are the kinds of issues that the European Union have been fighting Microsoft about over the past few years, and continue to fight them about.

If your version of Windows is current, you’ll notice the new addition in Firefox under Tools, Add-Ons, Extensions.

Microsoft .NET Framework Firefox Extension

Making matters worse, the uninstallation process is far from simple. Microsoft has also disabled the uninstall button in Firefox, and the removal process is a painstaking set of instructions found on Microsoft’s support website.

The issue was first discovered by the Washington Post’s Computer Security columnist, Brian Krebs, in an article entitled “Microsoft Update Quietly Installs Firefox Extension“. I personally first heard the issue through Steve Gibson’s and Leo Laporte’s Security Now podcast, episode 199. Steve does a great job explaining the little details and has quite an in depth discussion with Leo on the subject. I recommend checking these resources out it out if you would like more details.

Posted in Firefox, Open Source, Security

Firefox 3 is now the number one web browser in Europe!

Written on May 24th, 2009

Firefox Vs IE.. om nom nomIf you didn’t know already, as of last month, Firefox 3 has become the most popular browser in Europe! I am personally overjoyed by this occurrence and wish the Mozilla Foundation the best and much continued success.

This is a huge triumph for not only website developers, but also open source software as a whole. Before the Mozilla Foundation came onto the scene and released Firefox, the world of web browsers was in a depressing state. I wouldn’t doubt the majority of people reading this blog remember the post-Netscape, pre-Firefox days. I was graduating from highschool at the time and remember this era clearly.

Microsoft enjoyed a functional monopoly on the web browser market with their own Internet Explorer 6. As a result of Microsoft’s monopoly, web standards were for the most part thrown out the window, introduction of closed-proprietary features and formats were common, computer infection rates were very high and spyware ran rampant. At this time I frequented computer gaming events (LAN Parties!) with a number of my buddies. I remember us sharing our experiences about how ourselves, our friends and family members were constantly infected with malicious software contracted through Microsoft’s web browser. It was common to do a complete re-install of ones operating system every few months in order to keep things running at an acceptable level.

Feels good man.

Then out of nowhere, Firefox was released into the market. I admit, even I was a little skeptical to try it at first, yet I do remember that first day.. My good friend Andrew Almond insisted I try out this fantastic and fresh new browser, insisting a huge improvement over Microsoft’s offering; after which I did.

Installing Firefox was a breath of fresh air as my own computer infection problems nearly disappeared overnight! After about a month, the adoption of this new web browser exploded, and the thought of using Internet Explorer over Firefox became nearly laughable to us. The good word spread like wildfire.

Fast forward to now, Firefox is in its third iteration and better than ever. Microsoft has since had to clean up their act as a result, and there are now a number of very good web browsers on the market to choose from including Opera, Apple’s Safari and Google’s Chrome. Competition is great, and the Internet is generally a much safer place than it used to be.

Firefox is still my favored web browser, and of course, it holds a special place in my heart as it once symbolized a bright light in a dark era on the web, and continues to symbolize itself as a model open source project. Thank you, Firefox!

Firefox eating IE icon by Archangel-Daemon!

Posted in Firefox, Open Source

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