有限状态机应用是非常广泛的,比如关卡的切换、角色动画状态的切换等等,我自己写了个有限状态机,开发世嘉MD游戏的朋友可以用得到,对于解耦还是有点帮助的,不必挤在一个文件里。
没有学过MD游戏开发基础的可以翻看我写的基础篇教程。
C语言开发世嘉MD游戏-基础篇
https://blog.csdn.net/qq272508839/category_9528531.html
//=================================================
FSM.c文件代码如下:
#include <genesis.h>
#include "FSM.h"void initStateMgr(StateMgr *_stateMgr, u8 _stateCount)
{_stateMgr->preState = NULL;_stateMgr->curState = NULL;_stateMgr->stateList = MEM_alloc(sizeof(State) * _stateCount);for (u8 i = 0; i < _stateCount; i++){_stateMgr->stateList[i].ID = i;_stateMgr->stateList[i].enter = NULL;_stateMgr->stateList[i].stay = NULL;_stateMgr->stateList[i].exit = NULL;}_stateMgr->stateCount = _stateCount;
}void regStateEvent(StateMgr *_stateMgr, u8 _stateIndex, void (*_enter)(), void (*_stay)(), void (*_exit)())
{_stateMgr->stateList[_stateIndex].enter = _enter;_stateMgr->stateList[_stateIndex].stay = _stay;_stateMgr->stateList[_stateIndex].exit = _exit;
}void changeState(StateMgr *_stateMgr, u8 _stateIndex)
{if (_stateIndex < 0 || _stateIndex > _stateMgr->stateCount - 1)return;if (_stateMgr->stateList == NULL)return;if (_stateMgr->stateList[_stateIndex].enter == NULL)return;_stateMgr->preState = _stateMgr->curState;if (_stateMgr->preState != NULL && _stateMgr->preState->exit != NULL)_stateMgr->preState->exit();_stateMgr->curState = &(_stateMgr->stateList[_stateIndex]);if (_stateMgr->curState != NULL)_stateMgr->curState->enter();
}void updateState(StateMgr *_stateMgr)
{if (_stateMgr->curState != NULL)_stateMgr->curState->stay();
}
FSM.h头文件代码如下:
#ifndef _FSM_H_
#define _FSM_H_#include <genesis.h>typedef struct state
{u8 ID;void (*enter)(void);void (*stay)(void);void (*exit)(void);
} State;typedef struct statemgr
{u8 stateCount;State *preState;State *curState;State *stateList;
} StateMgr;//初始化状态管理,给_stateMgr分配内存
void initStateMgr(StateMgr *_stateMgr, u8 _stateCount);
//注册状态事件:enter,stay,exit
//_stateIndex是状态索引值
void regStateEvent(StateMgr *_stateMgr, u8 _stateIndex, void (*_enter)(), void (*_stay)(), void (*_exit)());
//改变状态
void changeState(StateMgr *_stateMgr, u8 _stateIndex);
//状态update
void updateState(StateMgr *_stateMgr);#endif