0

Hello! I am currently working on a text adventure in C++ and could use some help.

What I'm trying to do is let the user input a command like the following:
'go kitchen'
'open door with key'

and make the game react accordingly.
I have a text parser which splits any phrase into 4 tokens.

verb, object, preposition, object2.


But what I need to do then is somehow compare the input of the user to a list of available and valid commands. Any easy solution would be much appreciated since I have very little experience in programming.

so here is the string parser

struct command {
char* verb;
char* object;
char* preposition;
char* object2;
};

bool getTokens(char * acInput, 
           const char token_delimiter, 
           command * pTargetCommand)
{
char * pCurToken;

pCurToken = strtok (acInput, &token_delimiter);
if (pCurToken == NULL) {
    printf("Error: Found no verb");
    getchar();
    return 1;
}
pTargetCommand->verb = pCurToken;

pCurToken = strtok (NULL, &token_delimiter);
if (pCurToken == NULL) {
    printf("Error: Found no object");
    getchar();
    return 1;
}
pTargetCommand->object = pCurToken;

pCurToken = strtok (NULL, &token_delimiter);
if (pCurToken != NULL) {
    pTargetCommand->preposition = pCurToken;

    pCurToken = strtok (NULL, &token_delimiter);
    if (pCurToken == NULL) {
        printf("Error: Found no second object for preposition");
        getchar();
        return 1;
    }

    pTargetCommand->object2 = pCurToken;
}

pCurToken = strtok (NULL, &token_delimiter);
if (pCurToken != NULL) {
    printf("Error: too many tokens.");
    getchar();
    return 1;
}
}



int _tmain(int argc, _TCHAR* argv[])
  {
char acInput[256];
cin.getline (acInput,256);
command myCommand = { NULL };
int RoomChoice = 0;


printf ("Splitting string \"%s\" into tokens:\n", acInput);
getTokens(acInput, *TOKEN_DELIMITER, &myCommand);

printf ("Verb:        %s\n", myCommand.verb);
printf ("object:      %s\n", myCommand.object);
printf ("preposition: %s\n", myCommand.preposition);
printf ("object2:     %s\n", myCommand.object2);

getchar();

return 0;
  }
2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by L7Sqr
0

One way that might be effective for you is to create a syntax tree based on the commands you support. For instance, the root of the tree is empty and the first level of the tree is all the verbs you support. The node below each supported verb could be the set of objects valid for that verb. And so on...

This would work well for small languages but may become unwieldy as you include more command options. At that point you may look into a lexical analyzer that will verify input based on a specification. This route is certainly more advnaced.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.