Tuesday, November 2, 2010

Half-baked State Machines: Living with Regret

So I feel like programmers sometimes look at system that needs to be stratified into a state machine, and they ask themselves a very dangerous question "Do I really need to make this all that robust?" The answer should usually be STFU and write a decent state machine. I've had to deal with a state machine built on a switch statement that has now grown to over 2500 lines, which is the players character controller, and I want to smack the code's original author for giving me such a bee's nest to inherit.

Even with this most unfortunate experience under my belt, I still looked at a simple AI that I needed to write for my latest project, and thought "I bet I could get away with just a switch statement." In the end this is by and large a failure on my part, because even though the state machine get's the job done, I'm going to have to rewrite it if we decide to expand the scope of the game beyond the 4 weeks its currently set at.

Things that are important for any state machine:
1) Calling the active states update function each frame (or however frequent the state machine is supposed to act)
2) Letting the active state know when it is being exited
3) Informing the new active state that has just been entered

Anything that does not incorporate all 3 of these in a smooth and coherent manner can rapidly become a headache. This should be commons sense, but I've caught myself and another programmer falling into the same trap with this... So I figured it might be worth ranting about.

No comments:

Post a Comment