Sunday, May 8, 2016

architecture - Finite state machine in C++


So, I've read a lot about using FSMs to do game state management, things like what an FSM is, and using a stack or set of states for building one. I've gone through all that. But I'm stuck at writing an actual, well-designed implementation of an FSM for that purpose. Specifically, how does one cleanly resolve the problem of transitioning between states, (how) should a state be able to use data from other states, and so on. Does anyone have any tips on designing and writing a implementation in C++, or better yet, code examples?




Answer



I wrote a FSM based off of a chapter in "Massively Multiplayer Game Development" Edited by Thor Alexander. Inside is a chapter labelled "Parallel-State Machines for Believable Characters". This is written in python, but the concepts are easily translatable into C++. I highly recommend checking this out, even though this is about character states, not game states.


What I created is here: https://github.com/swganh/mmoserver/tree/master/src/ZoneServer/GameSystemManagers/State%20Manager look under StateManager for implementation details, but basically you have different 'base states' that you can use. Then from there you have the specific states that you transition to as a character, so every state is a class. You then check if can transition from one state to another and then on 'enter' you make your switch, you can also easily do things like put in events after moving to a state. I found this worked out really well for the game so far.


What I have implemented is what the book calls a parallel state machine, which is essential multiple fsm's working together, in this case you can transition into one state, that blocks all other states (ie: CreatureState_Dead). I'm not going to go too much more into detail as I don't think it would really help you, but if you'd like I can elaborate.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...