Friday, June 29, 2007

Game State Machine

Uses and Purpose:


A state machine has a context which holds the current state. Each state knows which states come next and when to transition to those states. There are many different ways of implementing a state machine. A lot of people like to use a State Manager class that knows which state to transition to and hold concurrent states, however this couples the Manager with each new state you create. This violates extensibility and abstraction principles of good design. The example state machine I have included is very extendable and abstracts the Conext (or State Manager) from the States themselves such that the Context only knows a bare minimum about the States that are running.

Design And Implementation Choices:


One of the concerns that must be addressed when creating a State Machine is whether your application is Multi-threaded or not. Since this example was created in Java your application most likely will have multiple threads. In C++ the code for a State Machine is trivial because most games are not multithreaded. Another concern is will you need substates my example code does not allow for substates but the State class can easily be sub-classed to hold substates or can also be done for concurrent states.


Code Speaks For Itself:


This example also includes Rendering Loop And Double Buffering example.

5 comments:

Anonymous said...

This is great info to know.

Marcello said...

Thank you so much !! Keep posting stuff :)

Thi Võ said...

i tried this, but i got a unexpected result, CPU used 100 and run slow... why?

Nick said...

Weirdness, I have never seen that happen with this example. Though I have been meaning to make a new example for this that isn't coupled with java.swing classes as much. But for debugging the high cpu issues for this snippet.

See Debugging High CPU usage for some things that might make a difference.

Thi Võ said...

Thank you for your kind assistance, I've just resolve that problem,just need change a bit
it's in the line create back buffer image
bufferImage=new BufferedImage(WIDTH_WINDOW, HEIGHT_WINDOW, BufferedImage.TYPE_INT_ABGR);
I change the third parameter to "...TYPE_INT_RGB" (just delete "A":D)or other types, very easy but it's costs me too much time ^^
thank you anyway

Post a Comment