nezvers

C state machine

Jan 15th, 2021 (edited)
362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. /*
  2. Github: https://github.com/nezvers
  3. Youtube: https://www.youtube.com/channel/UCb4-Y0E6mmwjtawcitIAzKQ
  4. Twitter: https://twitter.com/NeZversStudio
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9.  
  10. // State struct
  11. typedef struct{
  12.     void(*Enter)(void*);
  13.     void(*Exit)();
  14.     void(*Update)(float);
  15.     char *name;
  16. }State;
  17.  
  18. //StateMachine struct
  19. typedef struct{
  20.     State *state;
  21.     State *stateList;
  22. }StateMachine;
  23.  
  24. void change_state(StateMachine *sm, int stateIndex, void *data){
  25.     sm->state->Exit();
  26.     sm->state = &sm->stateList[stateIndex];
  27.     sm->state->Enter(data);
  28. }
  29.  
  30. // example data passed to state enter
  31. typedef struct {
  32.     int speed;
  33. }SomeData;
  34.  
  35. // Example state functions
  36. void st_idle_enter(void *data){
  37.     printf("Idle entered \n");
  38. }
  39. void st_run_enter(void *data){
  40.     int spd = ((SomeData*)data)->speed;
  41.     printf("Run entered with speed data: %d \n", spd);
  42. }
  43. void st_exit(){
  44.     printf("exited \n");
  45. }
  46. void st_update(float dt){
  47.     printf("delta_time: %f \n", dt);
  48. }
  49.  
  50. // State enum
  51. enum {
  52.     WALK,
  53.     RUN
  54. };
  55.  
  56. int main(){
  57.     State idle = {st_idle_enter, st_exit, st_update, "idle"};
  58.     State run = {st_run_enter, st_exit, st_update, "run"};
  59.     State list[] = {idle, run};
  60.     StateMachine sm = {&idle, list};
  61.    
  62.     sm.state->Update(0.666);
  63.     change_state(&sm, WALK, NULL);
  64.    
  65.     SomeData data = {16};
  66.     change_state(&sm, RUN, (void*)&data);
  67.    
  68.     return 0;
  69. }
Add Comment
Please, Sign In to add comment