状态驱动智能体设计——有限状态机(FSM)
1. 什么是有限状态机?
有限状态机,(英语:Finite-state machine, FSM),又称有限状态自动机,简称状态机,是表示有限个状态以及在这些状态之间的转移和动作等行为的数学模型。
2. 有限状态机的设计
设计者可以让角色持有一个有限状态机管理角色的不同状态,这个有限状态机也持有拥有它的角色。
有限状态机保存了当前状态、上一个状态、全局状态(全局状态总是长期存在于角色中,例如总是可以从任意状态切换到如厕状态),切换状态的方法、返回上一个状态的方法等。
每个状态都有进入、执行、退出方法,需要传进持有该状态的角色,以便状态可以达到某个状态让角色的有限状态机切换状态。
3. 核心代码展示
#ifndef STATEMACHINE_H
#define STATEMACHINE_H
//------------------------------------------------------------------------
//
// Name: StateMachine.h
//
// Desc: State machine class. Inherit from this class and create some
// states to give your agents FSM functionality
//
// Author: Mat Buckland 2002 (fup@ai-junkie.com)
//
//------------------------------------------------------------------------
#include <cassert>
#include <string>
#include "State.h"
template <class entity_type>
class StateMachine
{
private:
//a pointer to the agent that owns this instance
entity_type* m_pOwner;
State<entity_type>* m_pCurrentState;
//a record of the last state the agent was in
State<entity_type>* m_pPreviousState;
//this is called every time the FSM is updated
State<entity_type>* m_pGlobalState;
public:
StateMachine(entity_type* owner):m_pOwner(owner),
m_pCurrentState(NULL),
m_pPreviousState(NULL),
m_pGlobalState(NULL)
{}
virtual ~StateMachine(){}
//use these methods to initialize the FSM
void SetCurrentState(State<entity_type>* s){m_pCurrentState = s;}
void SetGlobalState(State<entity_type>* s) {m_pGlobalState = s;}
void SetPreviousState(State<entity_type>* s){m_pPreviousState = s;}
//call this to update the FSM
void Update()const
{
//if a global state exists, call its execute method, else do nothing
if(m_pGlobalState) m_pGlobalState->Execute(m_pOwner);
//same for the current state
if (m_pCurrentState) m_pCurrentState->Execute(m_pOwner);
}
//change to a new state
void ChangeState(State<entity_type>* pNewState)
{
assert(pNewState &&
"<StateMachine::ChangeState>: trying to change to NULL state");