Source

zorkish / CommandManager.hpp

Full commit
/*
 * CommandManager.hpp
 *
 *  Created on: 10/09/2012
 *      Author: rhys
 */

#ifndef COMMANDMANAGER_HPP_
#define COMMANDMANAGER_HPP_

#include <boost/algorithm/string/case_conv.hpp>
#include <forward_list>
#include "Command.hpp"
#include "util.hpp"

class CommandManager {
private:
    std::map<std::string, Command*> aliases;
    std::vector<std::unique_ptr<Command>> commands;

public:
    void add_command(std::unique_ptr<Command> cmd) {
        this->commands.push_back(std::move(cmd));
    }

    // alias must be uppercase
    void add_command(std::unique_ptr<Command> cmd, std::string alias) {
        this->add_alias(cmd.get(), alias);
        this->commands.push_back(std::move(cmd));
    }

    // aliases must be uppercase
    void add_command(std::unique_ptr<Command> cmd,
            std::initializer_list<std::string> aliases) {
        for (auto& s : aliases) {
            this->add_alias(cmd.get(), s);
        }
        this->commands.push_back(std::move(cmd));
    }

    // alias must be uppercase
    void add_alias(Command* cmd, std::string alias) {
        this->aliases[alias] = cmd;
    }

    bool run(World& world, Player& player) {
        std::string verb;
        std::string params;
        std::cin >> verb;
        getline(std::cin, params);
        boost::to_upper(verb);
        auto it = this->aliases.find(verb);
        if (it != end(this->aliases)) {
            if (!params.empty()) {
                params = params.substr(1, params.size() + 1);
            }
            std::cout << (*it).second->run(params, world, player) << "\n";
            return true;
        } else {
            std::cout << "I don't know how to do that.\n";
            return false;
        }
    }
};

#endif /* COMMANDMANAGER_HPP_ */