Page 1 of 1

State machine example

Posted: Thu Jul 25, 2013 9:46 pm
by CaptainMaelstrom
This topic hopes to achieve two things:

1.) be a springboard for anybody struggling to implement a basic state machine for their game.
2.) be a space for more experienced programmers to see potential pitfalls or helpful features I can remove/add to this state machine.

The example I'm posting is only a few hundred lines, and pretty well commented. I'll say a few things about it here, too, though.

I got the idea from Axel, who developed the AxGL framework for flash game development. See axgl.org.
The way he implements states is to have a "stack" of states. Then the developer can create new states, push them on the stack, remove them from the top, or switch a top state with another new state. It's a helpful way to organize a game, IMO.

He has a picture that shows the states he used in his game Diamond Hollow and how they stack together:
Image

And here is my .love example which you can dissect to see just how easy it is to implement yourself!

Re: State machine example

Posted: Fri Jul 26, 2013 1:14 am
by Shanulu
This is fantastic and lovely.

No questions thus far but I'll be sure to ask!

Re: State machine example

Posted: Fri Jul 26, 2013 5:01 am
by Davidobot
This looks interesting. Shouldn't this be in Projects and Demos?

Re: State machine example

Posted: Fri Jul 26, 2013 6:15 am
by CaptainMaelstrom
Davidobot wrote:Shouldn't this be in Projects and Demos?
Probably. I guess my reasoning was that it wasn't big enough in scope to really be considered a project or demo.

The mods can move it if they want.

Re: State machine example

Posted: Fri Jul 26, 2013 6:36 am
by Davidobot
CaptainMaelstrom wrote:
Davidobot wrote:Shouldn't this be in Projects and Demos?
Probably. I guess my reasoning was that it wasn't big enough in scope to really be considered a project or demo.

The mods can move it if they want.
Also you can check out my library, it is also centered around gamestates. It has support for stacked states too.

Re: State machine example

Posted: Fri Jul 26, 2013 7:10 am
by Plu
I also made this a while ago (but I wasn't very good with Lua, and still am not really):
http://love2d.org/forums/viewtopic.php? ... ck#p101246

Maybe you can scavenge some ideas from it :)

Re: State machine example

Posted: Fri Jul 26, 2013 7:37 am
by CaptainMaelstrom
Plu, Davidobot: Thanks for sharing.

I like a lot of what you've done especially Plu. I think I might borrow some ideas, like how you initialize your state objects with functions. This might solve my problem of having to choose between a State superclass and repeating code for separate State classes.

Also, I might try to incorporate all of my state machine functions into one table/object kind of like you have Davidobot. Not really necessary, but might be more elegant and stable.