状态机代码

2020-12-13  本文已影响0人  我的小诗
#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;
}
上一篇 下一篇

猜你喜欢

热点阅读