hayateasdf's blog

Unity,C#, javascript,C++,python,batなど

状態遷移のtemplate(適当)

#include <map>

template<class T>
class TState
{
	typedef void (T::*Func)();
	typedef std::map<int, Func> StateMap;
	typename typedef StateMap::iterator Itr;
	StateMap map_;
public:
	void Add(int id, Func func){ map_[id] = func;}
	void Run(T* _this, int id){ if(Find(id)) (_this->*map_[id])(); }
	bool Find(int id ){ return map_.count(id) != 0; }
};

class Hoge
{
private:
	enum STATE
	{
		ST_INIT,
		ST_LOAD,
		ST_UPDATE,
		ST_END,
	};
public:
	TState<Hoge> state_func_;
	int state_;
	int count_;
	Hoge()
	{
		state_func_.Add(ST_INIT, &Hoge::StInit);
		state_func_.Add(ST_LOAD, &Hoge::StLoad);
		state_func_.Add(ST_UPDATE, &Hoge::StUpdate);
		count_ = 0;
		state_ = ST_INIT;
	}
	void Action()
	{
		state_func_.Run(this, state_);
	}
	bool IsEnd(){ return state_ == ST_END; }
	void StInit()
	{
		printf("init\n");
		state_ = ST_LOAD;
	}
	void StLoad()
	{
		printf("loading\n");
		state_ = ST_UPDATE;
	}
	void StUpdate()
	{
		printf("update\n");
		if(count_ > 3)
			state_ = ST_END;
		else
			count_++;

		if(count_ == 1)
			state_ = ST_INIT;
	}
};
int main()
{
	Hoge hoge;
	while(true)
	{
		hoge.Action();
		if(hoge.IsEnd())
			break;
	}
	return 0;
}

f:id:hayateasdf:20141105230245p:plain