Hi, LeafyCircuits here!
Comp Specs:
OS: Windows 7 Home Premium 64-bit
Compiler: MinGW v4.6.2 running C++11
IDE: Code::Blocks v12.11
I've been wanting to create a mini-RPG/other game that uses commands that the user can invoke. For example, I want the user to be able to type something like this:
commandname [ARG1] [ARG2] [...] |
And would do something in-game. What I'm wondering is how to accomplish this in code. Actually defining a command that does something is easy enough, but it's actually parsing what the user typed and interpreting that to execute a command is complicated. I know I'll need a basic Tokenizer, so I created one myself:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class _BasicTokenizer
{
public:
void tokenize(string str, char delimiter=' ')
{
string tokenbuf;
for (int i=0;i<str.length();i++)
{
if (str[i]==delimiter)
{
tokens.push_back(tokenbuf);
tokenbuf="";
}
else
{
tokenbuf+=str[i];
}
}
tokens.push_back(tokenbuf);
}
vector<string> returnTokens() {return tokens;}
vector<string> TokenizeAndReturn(string somestr, char adelimiter=' ')
{
tokenize(somestr, adelimiter);
returnTokens();
}
private:
vector<string> tokens;
};
|
After that, I'm not sure how to approach this. One thing I've tried is creating a class that has all the commands, then create another class that handles the parsing, then calls the appropriate function through the use of function pointers; that got messy pretty quickly. Having a separate typedef for every function with different args and return values would get very cluttered and disorganized. So I scraped this idea, but I feel like I'll need another class to do the parsing at least, I just don't know where to go from here.
So, that leads to one of the things I'm wondering: is there a design pattern for this? I'm sure I'm not the only one to have thought of in-game commands, so maybe there is a basic design pattern, or at least, pattern of thought.
What I'm basically asking is for anybody more experienced in this to help me out :)
Any and all help is appreciated.