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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <iostream>
#include <string>
#include <map>
#include <functional>
#include <sstream>
void open_door() { std::cout << "open the door\n" ; /* ... */ }
void take_object() { std::cout << "add object to inventory\n" ; /* ... */ }
void use_object() { std::cout << "do something with object\n" ; /* ... */ }
enum direction { N = 'N', S = 'S', E = 'E', W = 'W' } ;
void walk( direction dir )
{ std::cout << "move one square towards " << char(dir) << '\n' ; /* ... */ }
// lookup maps commands as pair of strings to function
const std::map< std::pair< std::string, std::string >, std::function< void() > > cmd_map =
{
{ { "open", "door" }, open_door },
{ { "take", "object" }, take_object },
{ { "use", "object" }, use_object },
{ { "walk", "n" }, std::bind( walk, N ) },
{ { "walk", "e" }, std::bind( walk, E ) },
{ { "walk", "s" }, std::bind( walk, S ) },
{ { "walk", "w" }, std::bind( walk, W ) }
};
bool process( const std::string& command )
{
std::istringstream stm(command) ;
std::string verb, noun ;
if( stm >> verb >> noun && stm.eof() )
{
auto iter = cmd_map.find( std::make_pair( verb, noun ) ) ;
if( iter != cmd_map.end() ) { iter->second() ; return true ; }
}
return false ;
}
int main()
{
std::string cmd ;
while( std::cout << "command> " && std::getline( std::cin, cmd ) )
{
for( char& c : cmd ) c = std::tolower( c, std::cin.getloc() ) ;
if( cmd == "exit" ) break ;
else if( !process(cmd) )
std::cerr << "do not understand the coomand: '" << cmd << "'\n" ;
}
}
|