So, the FSM is kinda cool when you get the whole idea. I only started with the coin unlock to test out, and I would like you guys could give me more advice if i'm not on the right track.
so this is the states.h file:
and this is the FSM.hCode:class State { public: State(){} ~State(){} char sName[50]; int sType, sOrder; //Dont mind the 'sType'. it's not doing anything void setupState(int type, int order, char* name); }; void State::setupState(int type, int order, char *name) { sType = type; sOrder = order; strcpy(sName, name); }
and finally, the main CPPCode:#ifndef fsm_h #define fsm_h #include <vector> #include <iostream> #include "states.h" class FSM { public: int CurrentStateNumber; FSM() { CurrentStateNumber = 0; } ~FSM(){} std::vector<State>CurrentState; void addState(State state) { CurrentState.push_back(state); } void getAction(char* actionName) { int nextStateNumber = 0; if(CurrentStateNumber == 2) { nextStateNumber = 0; }else nextStateNumber = CurrentStateNumber+1; if( strcmp(CurrentState[CurrentStateNumber].sName, actionName) == 0 || strcmp(CurrentState[nextStateNumber].sName, actionName) != 0) { std::cout<<"You've entered an invalid state"; std::cout<<"\nYou're on '"<<CurrentState[CurrentStateNumber].sName<<"' state"<<std::endl; return; }else { CurrentStateNumber = nextStateNumber; std::cout<<"You're on the '"<<CurrentState[CurrentStateNumber].sName<<"' state"<<std::endl; } } }; #endif
So what do u guys think? Do u think the process of the code is ok for FSM. I appreciate for any advice. thanksCode:#include <iostream> #include "states.h" #include "FSM.h" using namespace std; FSM fsm; State cState[3]; char command; void Init() { //Dont worry about the Order number (0, 1, 2). I did not do anything with them. cState[0].setupState(0, 0, "lock"); cState[1].setupState(0, 1, "coin"); cState[2].setupState(0, 2, "unlock"); for(int j=0; j< 3; j++) { fsm.addState(cState[j]); } } int main(int argc, char* argv[]) { Init(); do{ cout<<"\nEnter the command (l, c, u) or q to quit: "; cin>>command; switch(command) { case 'l': fsm.getAction("lock"); break; case 'c': fsm.getAction("coin"); break; case 'u': fsm.getAction("unlock"); break; case 'q': break; default: break; } }while(command != 'q'); std::cout<<'\n'; return 0; }



LinkBack URL
About LinkBacks




Want to add some