c++ 控制前后左右移动,把这四段类似代码用简化方式整合成一段,求编写好的代码

img

img

img

要求控制一个点东南西北房间的移动。用一种方法简化四段代码为一段来控制东南西北房间进行移动。求编译后的代码

#define N_DIR 4

typedef enum _roomDir
{
    no_room = 0,
    room_east = 1,
    room_south= 2,
    room_west = 3,
    room_north= 4,
}roomDir;

string dir[N_DIR] = {"east","south","west","north"};
string dir_s[N_DIR] = {"e","s","w","n"};
 
roomDir getDir(string commandBuffer)
{
    for(int i=1;i<=N_DIR;i++)
    {
        if((commandBuffer.compare(0,endOfVerb,dir[i]) == 0) || (commandBuffer.compare(0,endOfVerb,dir_s[i]) == 0))
            return (roomDir)i;
    }
    return no_room;
}

Room * getRoom(roomDir eRoomDir)
{
    switch(eRoomDir)
    {
    case room_east:
        return currentState->getCurrentRoom()->getEast();
    case room_south:
        return currentState->getCurrentRoom()->getSouth();
    case room_west:
        return currentState->getCurrentRoom()->getWest();
    case room_north:
        return currentState->getCurrentRoom()->getNorth();
    }
    return NULL;
}

void fun(string commandBuffer)
{
    roomDir rd = getDir(commandBuffer);
    Room *pRoom = getRoom(rd);
    if(pRoom != NULL)
    {
        commandOK = true;
        currentState->goTo(pRoom);
    }
    else
    {
        wrapOut(&badExist);
        wrapEndPara();
    }
}