CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2006
    Posts
    54

    Calling functions based on inputs

    Anyone ever play a MUD before? Usually, it's a telnet based game where you're in a fantasy world, and you enter commands to make your character move, chat, attack monsters, etc. Deep down, though, all that is happening is that the user inputs a command, the server does something based on that command, and the user gets an output. I wish to create a scalable command system.

    A few commands are like the following:

    attack <target> --- attack imp
    sit <object (optional)> --- sit chair
    move(direction) --- w
    say <chat string> --- say hello thar buddy!

    Each one has different base commands and uses the additional parameters in different ways.

    I always think worst-case scenario, so when I see this problem, I think of the possibility of hundreds of different base commands, each one using parameters in different ways. Obviously, if I used an if/else chain to call the appropriate function for each command, it would take O(n) time which is not acceptable for a long list of commands.

    There was another method I was thinking of, but I have no idea if it's even possible. Create a simple struct containing two things: the command name and the function name. I could then develop a search algorithm (possibly binary) to find the command, then execute the function accompanying it.

    Any help would be greatly appreciated.

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Calling functions based on inputs

    There was another method I was thinking of, but I have no idea if it's even possible. Create a simple struct containing two things: the command name and the function name. I could then develop a search algorithm (possibly binary) to find the command, then execute the function accompanying it.
    That sounds possible. Another possibility is to use a std::map (or a hash map, with say, std::tr1::unordered_map, I think) to map the commands to say, their respective function pointers or perhaps function objects.

    The function object approach may be better in the sense that once you have obtained the function object based on the command name, you can use operator overloading to call the correct operator() based on the arguments supplied by the user input.
    Last edited by laserlight; November 24th, 2007 at 02:18 PM.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured