表驅動的二級狀態機實現

2021-10-20 12:38:56 字數 3190 閱讀 3410

最後總結

一級狀態機和二級狀態機的區別是:二級狀態機在一級狀態機的基礎上新增了很多子狀態,(子狀態共同擁有上級父狀態的某些共性,又各自擁有自己的一些共性)。狀態表需要分為兩級。

看過表驅動的一級狀態機實現 和 指標陣列 這兩篇文章的小夥伴應該已經知道我寫的這二級狀態機是怎麼實現的了,測試程式邏輯的main函式也和一級狀態機的大同小異。

/* 指標陣列 */

static stateinfo *statetable=

;/* 狀態機資料結構 */

typedef

struct

statemachine;

void

state_machine_regist

(statemachine *psm, stateinfo *pstatetable)

;stateinfo *

find_state_table

(statemachine *psm, event evt)

;void

runstatemachine

(statemachine *psm, event evt)

;#endif

#include

"statemachine2.h"

void

action_callback

(void

)/* 狀態機註冊,給它乙個狀態表 */

void

state_machine_regist

(statemachine *psm, stateinfo *pstatetable)

psm-

>statetable = pstatetable;

}/* 查詢狀態表 */

stateinfo *

find_state_table

(statemachine *psm, event evt)

for(

uint8_t i =

0; i < psm-

>statetablenum; i++)}

}/* 執行狀態機 */

void

runstatemachine

(statemachine *psm, event evt)

pstateinfo =

find_state_table

(psm, evt);if

(pstateinfo ==

null

) action_func act = pstateinfo-

>action;

if(act ==

null

)act()

; psm-

>currentstate = pstateinfo-

>nextstate;

}

_state_table(psm, evt);

if (pstateinfo == null)

action_func act = pstateinfo->action;

if (act == null)

act();

psm->currentstate = pstateinfo->nextstate;

## 最後總結

到此為止已經對狀態機有一定程度的掌握了,兩個程式都是表驅動的(跳轉表),我覺得這樣實現對於後期維護比較友好,我對現在的微控制器程式設計工作的認識是需求只增不減,只改不刪,每次隔上一段時間後改需求自己一下子都搞不清要改哪幾處,雖然目前積極在寫功能模組的說明,將程式分而化之,可以對功能實現細節有更好的把控,但逐漸意識到更需要乙個好的結構,我之前認為形成自己的程式設計風格,積累相關的技術文件就能寫出好的程式來,至於什麼是程式架構,沒聽說過,更別說它能起到什麼樣的作用了,之後打算寫幾篇這方面的博文,現在嘛,還未準備充分。

qt狀態機的實現

建立狀態,設定狀態中的屬性,設定初始狀態,設定狀態裝換條件 動畫,啟動狀態機 int nmargin 9 int ninitwidth m pselmoldform width int ninitheight m pselmoldform height int nconfepyformw m pco...

有限狀態機的實現

有限狀態機 finite state machine或者finite state automata 是軟體領域中一種重要的工具,很多東西的模型實際上就是有限狀態機。最近看了一些遊戲程式設計ai的材料,感覺遊戲中的ai,第一要說的就是有限狀態機來實現精靈的ai,然後才是a 尋路,其他學術界討論比較多的...

Python 狀態機模式的實現

原因 解決 冗餘處理效率低的問題 原有模式 class connection 普通方案,好多個判斷語句,效率低下 def init self self.state closed defread self if self.state open raise runtimeerror not open p...