views:

57

answers:

2

We are making a game with a playing character that will have several different states. In most examples I see a switch statement in the controllable charactor based on the state. Is this the standard way that things are done for most games? Or is it better to create a set of states that handle the animation and logic of that state. It seems like the latter would create a lot of classes that may not be necessary but would have more flexibility. The case statements would make the code more messy but would have less overall files. I know that for AI type functions it would be better to use the state model. I guess what I am getting at, should i be making a state object for simple things as 'walkleft', 'walkright'? Or is there a better way to do things that i'm missing?

Thanks, hope this is clear enough.

A: 

Consider using a jump table (aka. branch table or more likely a function or method table nowadays) as a middle ground between simple case statements and a full-blown state machine.

John Lemberger
+2  A: 

It all depends on how large your switch statement is. I would, personally, lean toward making a bunch of state objects. If you end up having a bunch of files because of that, so be it. That will probably make the code easier to understand, because each state is a module that has less chance of other code interfering with it. When you try to reason about the behavior of a state, there will less miscellaneous code to distract you.

It is good practice to break your design down into small pieces so you can code and, if at all possible, test them as standalone modules. This will make your debugging much easier. You don't need to get too carried away with modularizing everything, but I would lean toward many small classes instead of a few huge awkward ones.

You are right to be a little wary of creating things which are not necessary. Too much flexibility ends up being a pain to maintain. Just make it flexible enough to handle your current problem. Don't put too much effort into solving hypothetical future needs. Focus on what you need now. You observe that a large switch statement with lots of cases would make the code messy. I think that gives you your answer right there. Tend toward simple code with small functions, and small classes. Sure you will have a lot of them, but it is a lot easier to grasp how many small functions fit together, than how myriads of statements stacked on top of each other in a gargantuan function fit together.

A. Levy