Skip to content

Instantly share code, notes, and snippets.

@utilForever
Created September 2, 2016 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save utilForever/0b2581118640dc01a3685658ce2e97a2 to your computer and use it in GitHub Desktop.
Save utilForever/0b2581118640dc01a3685658ce2e97a2 to your computer and use it in GitHub Desktop.
Finite State Machine Example
#include <iostream>
#include <string>
enum States { IDLE, MOVE, YUMYUM, EAT, DIE, CLEAR, FINISH };
void RunLogic(States);
int main()
{
// FSM : Finite State Machine (유한 상태 기계)
// State : 상태 (Idle, Move, Eat, ...)
// Codition : 상태 변경을 위한 조건 (방향키를 누른다, 적과 충돌한다, ...)
// 1. 초기 상태
States s = IDLE;
// 2. FSM 함수 호출
// 4. 반복 조건 성립
while (!(s == CLEAR || s == DIE))
{
RunLogic(s);
}
}
// 3. FSM 구현
void RunLogic(States s)
{
switch (s)
{
case IDLE:
if (방향키를 움직였다) s = MOVE;
else if (적과 충돌했다) s = DIE;
break;
case MOVE:
if (물약을 먹었다) s = YUMYUM;
else if (적과 충돌했다) s = DIE;
else if (구슬을 모두 먹었다) s = CLEAR;
break;
case YUMYUM:
if (적과 충돌했다) s = EAT;
else if (물약 시간이 다 되었다) s = MOVE;
else if (구슬을 모두 먹었다) s = CLEAR;
break;
case EAT:
if (먹었다) s = YUMYUM;
break;
case DIE:
// 죽었을 때 처리
s = FINISH;
break;
case CLEAR:
// 승리 처리
s = FINISH;
break;
default:
// 망했다
throw std::logic_error("Invalid State! WTF!\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment