Considering you re starting at, we can look at this in the simple case first, but you can t use a switch
statement to achieve this.
Let s assume, for the purposes of simplicity, that your commands are limited to 1 or 2 words and that the first word is a verb and the second would, if present is a noun. This gives us quite a few possibilities:
North
South
Examine
Take
Drop
etc...
Given that we have an input string of strInput
:
string strInput = "examine hat";
We want to first split this up. We can do this using String.Split
:
string[] arguments = strInput.Split( );
Which will give us a string array:
arguments [0] is examine
arguments [1] is hat
Note, we don t always have a the 2nd one, if the user typed:
`North`
then:
arguments [0] is North
We ll need to check for this! Now, the horrible (but simple) way to check for this is:
if(arguments[0] == "North")
{
// code to go North
}
else if(arguments[0] == "Take")
{
// code to work with Take. We d check on arguments[1] here!
}
// etc...
Unfortunately, this code is going to get long, complex and unusable. How do you know what you can and can t do at any stage? How do you add new command? So let s use the wonderful delegate feature of C#, and also introduce the Dictionary
. A dictionary allows us to map one type (a key) to another (in this case, a delegate). Using this method, we can create delegates to handle different kinds of commands.
public delegate void HandleCommand(string[] _input);
Here, we delegated a delegate. Don t worry about it yet, but let s introduce some functions that will work with commands:
public void Handle_North(string[] _input)
{
// code to go North. This function could just as easily be something that handles
// *all* directions and checks _input[0] to see where to go!
}
public void Handle_Take(string[] _input)
{
if(_input.Length > 1) // Did the user specify an object to take?
{
// code to handle Take.
}
}
And so on. Now we need to create a dictionary to map the commands to these functions:
Dictionary<String, HandleCommand> map = new Dictionary<String, HandleCommand>();
Here, we declare a dictionary that maps strings to our delegate type HandleCommand
. Now we need to populate it!
map["north"] = Handle_North;
map["take"] = Handle_Take;
// and the rest of our commands
Now, given our earlier example, let s split the string up as before, and call the right handler!
string[] arguments = strInput.Split( );
if(arguments.Length > 0 && map.ContainsKey(arguments[0]))
map[arguments[0]](arguments); // calls our function!
Now we have an extensible system. It is easy to add new commands and handlers! It gets more complicated, but in essence this is a good way to do what you want.
EDIT: I am aware that your question said that it should not care about the order of the words. If you re writing a text adventure game, you d do well to form some grammer of Verb/Noun or some such rather than allowing things to be typed randomly.