狀態機代碼

#include <stdio.h> typedef enum { EV_STOP, EV_PLAY_PAUSE } EventCode; typedef enum { ST_IDLE, ST_PLAY, ST_PAULE } State; static State state; void initialize() { state = ST_IDLE; } void stopPlayer() { state = ST_IDLE; } void pausePlayer() { state = ST_PAULE; } void resumePlayer() { state = ST_PLAY; } void startPlayer() { state = ST_PLAY; } void onEvent(EventCode ec) { if(ec == EV_PLAY_PAUSE) printf("play pause key pressed\n"); else if(ec == EV_STOP) printf("stop key pressed\n"); switch(state) { case ST_IDLE: if(ec == EV_PLAY_PAUSE) startPlayer(); break; case ST_PLAY: if(ec == EV_PLAY_PAUSE) pausePlayer(); else if(ec == EV_STOP) stopPlayer(); break; case ST_PAULE: switch(ec) { case EV_STOP: stopPlayer; break; case EV_PLAY_PAUSE: startPlayer(); break; default: break; } default: break; } //printf("state %d\n", state); if(state == ST_IDLE) printf("current player state is idle\n"); else if(state == ST_PAULE) printf("current player state is pause\n"); else if(state == ST_PLAY) printf("current player state is playing\n"); } int main(void){ initialize(); onEvent(EV_PLAY_PAUSE); onEvent(EV_PLAY_PAUSE); onEvent(EV_PLAY_PAUSE); onEvent(EV_STOP); return 0; }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章