序言:世间万物皆为状态机,状态机在编程过程中使用的十分广泛。使用一个好的状态机类,可使程序有条理,业务逻辑清晰。在 github上有一个经典的状态机 r-lyeh v1.0.0。该状态机支持C++11,单头文件,轻量级,跨平台,支持函数对象(std :: function),可绑定函数回调,类成员函数,lambda表达式。功能非常强大,使用非常方便,是一个不错的C++类,值得推荐。https://github.com/r-lyeh-archived/fsm
1.简单使用
传统方式:面向过程,很大一个switch结构
switch(state){
case state0:std::cout << "进入状态0" << std::endl;break;
case state1:std::cout << "进入状态1" << std::endl;break;
case state2:std::cout << "进入状态2" << std::endl;break;
case state3:std::cout << "进入状态3" << std::endl;break;
case state4:std::cout << "进入状态4" << std::endl;break;
//......
}
使用状态机类:面向对象,思路清晰明了
#include "fsm.hpp"
fsm::stack fsm;//定义一个状态机变量
//事件绑定
fsm.on('state0', 'init') = [&]( const fsm::args &args ) {
std::cout << "进入状态0" << std::endl;
};
fsm.on('state0', 'quit') = [&]( const fsm::args &args ) {
std::cout << "状态0结束" << std::endl;
};
fsm.on('state1', 'init') = [&]( const fsm::args &args ) {
std::cout << "进入状态1" << std::endl;
};
fsm.on('state1', 'quit') = [&]( const fsm::args &args ) {
std::cout << "状态1结束" << std::endl;
};
fsm.on('state2', 'init') = [&]( const fsm::args &args ) {
std::cout << "进入状态2" << std::endl;
};
fsm.on('state2', 'quit') = [&]( const fsm::args &args ) {
std::cout << "状态2结束" << std::endl;
};
//......
fsm.set('state0');//进入状态state0
2.源码自带示例
先看一下源码自带的示例,了解如何使用该状态机类。
示例使用状态机实现一个小游戏,一只蚂蚁战士在家与丛林之间不断地巡逻,在某个时间蚂蚁受到敌人攻击,进入防御状态,血量持续减少,当血量为0时,恢复巡逻状态,继续巡逻。
╮╭
╭─╮ ╭─────╮
( 0 )═{ ﹝﹝﹝ }
╰─╯ ╰─────╯
╯╯ ╰╰
状态表:
| 状态名 | 事件 | function名
─────────────────
| 行走 | 初始化 | init
| 行走 | 结束 | quit
| 行走 | 暂停 | push
| 行走 | 恢复 | back
| 行走 | 刷新 | tick
| 防御 | 初始化 | init
| 防御 | 刷新 | tick
3.源码自带示例分析:
#include <iostream>
// custom states (gerunds) and actions (infinitives)
enum {
walking = 'WALK',//走路状态,注:单引号表示不是字符串,实际是一个整形,也可设置为一个整数
defending = 'DEFN',//防御状态
tick = 'tick'//刷新
};
struct ant_t {
fsm::stack fsm;
int health, distance, flow;
ant_t() : health(0), distance(0), flow(1) {
// define fsm transitions: on(state,trigger) -> do lambda
fsm.on(walking, 'init') = [&]( const fsm::args &args ) {//行走状态,绑定init函数(初始化)
std::cout << "initializing" << std::endl;
};
fsm.on(walking, 'quit') = [&]( const fsm::args &args ) {//行走状态,绑定quit函数(状态结束时清理)
std::cout << "exiting" << std::endl;
};
fsm.on(walking, 'push') = [&]( const fsm::args &args ) {//行走状态,绑定push函数,暂停时执行
std::cout << "pushing current task." << std::endl;
};
fsm.on(walking, 'back') = [&]( const fsm::args &args ) {//行走状态,绑定back函数,恢复时执行
std::cout << "back from another task. remaining distance: " << distance << std::endl;
};
fsm.on(walking, tick) = [&]( const fsm::args &args ) {//行走状态,定义一个tick动作,用于输出一些信息
std::cout << "\r" << "\\|/-"[ distance % 4 ] << " walking " << (flow > 0 ? "-->" : "<--") << " ";
distance += flow;
if( 1000 == distance ) {
std::cout << "at food!" << std::endl;
flow = -flow;
}
if( -1000 == distance ) {
std::cout << "at home!" << std::endl;
flow = -flow;
}
};
fsm.on(defending, 'init') = [&]( const fsm::args &args ) {//防御状态,绑定init函数(初始化)
health = 1000;
std::cout << "somebody is attacking me! he has " << health << " health points" << std::endl;
};
fsm.on(defending, tick) = [&]( const fsm::args &args ) {//行走状态,定义一个tick动作,用于输出一些信息
std::cout << "\r" << "\\|/-$"[ health % 4 ] << " health: (" << health << ") ";
--health;
if( health < 0 ) {
std::cout << std::endl;
fsm.pop();//血量小于0,结束本状态,恢复为之前的状态
}
};
// set initial fsm state
fsm.set( walking );//初始化状态为行走状态
}
};
int main() {
ant_t ant;//创建一个蚂蚁战士(状态机)
for(int i = 0; i < 12000; ++i) {//满足条件时进入防御状态,战士受到攻击,攻击完成自动恢复为行走状态
if( 0 == rand() % 10000 ) {
ant.fsm.push(defending);
}
ant.fsm.command(tick);//刷新每一帧,输出一些信息
}
}
源代码还有一个CD播放器的例子,大家自行去研究。
4.状态机类fsm实现原理
关键变量:std::map< bistate, fsm::call > callbacks; 实际为一个表,绑定状态和其对应事件的function
关键函数:bool call( const fsm::state &from, const fsm::state &to ), 从表中查找指定状态的指定动作对应的函数回调并执行
在stack结构中有一个表,保存的是每个状态及其所有动作对应的function(即C++11中的std :: function,可以存储,复制和调用任何可调用的目标 :包括函数,lambda表达式,绑定表达式或其他函数对象,以及指向成员函数和指向数据成员的指针),当状态发生变化时会从表中查找到要执行的函数回调并执行。
- 每个状态机都有'init', 'quit', 'push', 'back'四个标准事件,在适当时机自动调用
- init:在进入某一状态时自动调用 ;quit在某一状态结束时自动调用
- push:将某一状态暂停时自动调用;back:将某一状态恢复时自动调用
- 注意:每个状态的四个标准要自己实现并绑定,如果没有实现,则不调用
- 使用set设置初始状态或改变当前状态
5.源码分析:
fsm.hpp
#pragma once
#define FSM_VERSION "1.0.0" /* (2015/11/29) Code revisited to use fourcc integers (much faster); clean ups suggested by Chang Qian
#define FSM_VERSION "0.0.0" // (2014/02/15) Initial version */
#include <algorithm>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
namespace fsm
{
template<typename T>//模板函数,实现任意类型数据转换字符串
inline std::string to_string( const T &t ) {
std::stringstream ss;
return ss << t ? ss.str() : std::string();
}
template<>
inline std::string to_string( const std::string &t ) {
return t;
}
typedef std::vector<std::string> args;
typedef std::function< void( const fsm::args &args ) > call;
struct state {//代表状态
int name;
fsm::args args;
state( const int &name = 'null' ) : name(name)//使用整形初始化一个状态
{}
state operator()() const {//运算符重载,返回状态自己
state self = *this;
self.args = {};
return self;
}
template<typename T0>
state operator()( const T0 &t0 ) const {//设置状态的数据t0,并转换成字符串保存
state self = *this;
self.args = { fsm::to_string(t0) };
return self;
}
template<typename T0, typename T1>
state operator()( const T0 &t0, const T1 &t1 ) const {//设置状态的数据t0 t1
state self = *this;
self.args = { fsm::to_string(t0), fsm::to_string(t1) };
return self;
}
operator int () const {
return name;
}
bool operator<( const state &other ) const {
return name < other.name;
}
bool operator==( const state &other ) const {
return name == other.name;
}
template<typename ostream>
inline friend ostream &operator<<( ostream &out, const state &t ) {//打印一个状态
if( t.name >= 256 ) {
out << char((t.name >> 24) & 0xff);
out << char((t.name >> 16) & 0xff);
out << char((t.name >> 8) & 0xff);
out << char((t.name >> 0) & 0xff);
} else {
out << t.name;
}
out << "(";
std::string sep;
for(auto &arg : t.args ) {
out << sep << arg;
sep = ',';
}
out << ")";
return out;
}
};
typedef state trigger;
struct transition {
fsm::state previous, trigger, current;
template<typename ostream>
inline friend ostream &operator<<( ostream &out, const transition &t ) {
out << t.previous << " -> " << t.trigger << " -> " << t.current;
return out;
}
};
class stack {//保存状态的容量
public:
stack( const fsm::state &start = 'null' ) : deque(1) {//使用一个状态初始化容器
deque[0] = start;
call( deque.back(), 'init' );//执行init函数
}
stack( int start ) : stack( fsm::state(start) )
{}
~stack() {
// ensure state destructors are called (w/ 'quit')
while( size() ) {
pop();//执行每个状态的qiut函数
}
}
// pause current state (w/ 'push') and create a new active child (w/ 'init')
void push( const fsm::state &state ) {//暂停一个状态
if( deque.size() && deque.back() == state ) {
return;
}
// queue
call( deque.back(), 'push' );//执行上一个状态push函数
deque.push_back( state );
call( deque.back(), 'init' );//执行新状态的init函数
}
// terminate current state and return to parent (if any)
void pop() {//恢复一个状态
if( deque.size() ) {
call( deque.back(), 'quit' );//执行当前状态的qiut函数
deque.pop_back();
}
if( deque.size() ) {
call( deque.back(), 'back' );//执行下一个状态的back函数(待恢复的状态)
}
}
// set current active state
void set( const fsm::state &state ) {//设置当前状态为state ,并自动执行相关函数
if( deque.size() ) {
replace( deque.back(), state );
} else {
push(state);
}
}
// number of children (stack)
size_t size() const {
return deque.size();
}
// info
// [] classic behaviour: "hello"[5] = undefined, "hello"[-1] = undefined
// [] extended behaviour: "hello"[5] = h, "hello"[-1] = o, "hello"[-2] = l
fsm::state get_state( signed pos = -1 ) const {//获取当前状态
signed size = (signed)(deque.size());
return size ? *( deque.begin() + (pos >= 0 ? pos % size : size - 1 + ((pos+1) % size) ) ) : fsm::state();
}
fsm::transition get_log( signed pos = -1 ) const {
signed size = (signed)(log.size());
return size ? *( log.begin() + (pos >= 0 ? pos % size : size - 1 + ((pos+1) % size) ) ) : fsm::transition();
}
std::string get_trigger() const {
std::stringstream ss;
return ss << current_trigger, ss.str();
}
bool is_state( const fsm::state &state ) const {
return deque.empty() ? false : ( deque.back() == state );
}
/* (idle)___(trigger)__/''(hold)''''(release)''\__
bool is_idle() const { return transition.previous == transition.current; }
bool is_triggered() const { return transition.previous == transition.current; }
bool is_hold() const { return transition.previous == transition.current; }
bool is_released() const { return transition.previous == transition.current; } */
// setup
fsm::call &on( const fsm::state &from, const fsm::state &to ) {//返回表中绑定的一个匿名函数
return callbacks[ bistate(from,to) ];
}
// generic call
bool call( const fsm::state &from, const fsm::state &to ) const {
std::map< bistate, fsm::call >::const_iterator found = callbacks.find(bistate(from,to));
if( found != callbacks.end() ) {
log.push_back( { from, current_trigger, to } );
if( log.size() > 50 ) {
log.pop_front();
}
found->second( to.args );
return true;
}
return false;
}
// user commands
bool command( const fsm::state &trigger ) {//执行trigger 函数
size_t size = this->size();
if( !size ) {
return false;
}
current_trigger = fsm::state();
std::deque< states::reverse_iterator > aborted;
for( auto it = deque.rbegin(); it != deque.rend(); ++it ) {
fsm::state &self = *it;
if( !call(self,trigger) ) {
aborted.push_back(it);
continue;
}
for( auto it = aborted.begin(), end = aborted.end(); it != end; ++it ) {
call(**it, 'quit');
deque.erase(--(it->base()));
}
current_trigger = trigger;
return true;
}
return false;
}
template<typename T>
bool command( const fsm::state &trigger, const T &arg1 ) {
return command( trigger(arg1) );
}
template<typename T, typename U>
bool command( const fsm::state &trigger, const T &arg1, const U &arg2 ) {
return command( trigger(arg1, arg2) );
}
// debug
template<typename ostream>
ostream &debug( ostream &out ) {
int total = log.size();
out << "status {" << std::endl;
std::string sep = "\t";
for( states::const_reverse_iterator it = deque.rbegin(), end = deque.rend(); it != end; ++it ) {
out << sep << *it;
sep = " -> ";
}
out << std::endl;
out << "} log (" << total << " entries) {" << std::endl;
for( int i = 0 ; i < total; ++i ) {
out << "\t" << log[i] << std::endl;
}
out << "}" << std::endl;
return out;
}
// aliases
bool operator()( const fsm::state &trigger ) {//执行带参数的函数
return command( trigger );
}
template<typename T>
bool operator()( const fsm::state &trigger, const T &arg1 ) {
return command( trigger(arg1) );
}
template<typename T, typename U>
bool operator()( const fsm::state &trigger, const T &arg1, const U &arg2 ) {
return command( trigger(arg1, arg2) );
}
template<typename ostream>
inline friend ostream &operator<<( ostream &out, const stack &t ) {
return t.debug( out ), out;
}
protected:
void replace( fsm::state ¤t, const fsm::state &next ) {//替换某一状态
call( current, 'quit' );
current = next;
call( current, 'init' );
}
typedef std::pair<int, int> bistate;
std::map< bistate, fsm::call > callbacks;
mutable std::deque< fsm::transition > log;
std::deque< fsm::state > deque;//状态列表,最后一个为当前状态,前面的为暂停的状态
fsm::state current_trigger;//当前状态
typedef std::deque< fsm::state > states;
};
}