c++ - 有没有更优雅的方法来实现 C++ 游戏的 "cheat code"实现?

标签 c++ refactoring

我一直在通过深入研究一个项目(一个简单的 2d 游戏)来学习 C++。我试图实现一组作弊,但我在字符串操作方面是个新手。我确信会有比下面的代码更优雅的方式来实现我想要的。

根据要求,stringBuffer 只是一个包含最后 12 个按下字符的字符串。我把它放在前面是因为它在最后调整大小后被修剪,因此我的秘籍必须倒退。我在字符串操作方面非常菜鸟,我知道这里有问题,这就是为什么我要求对其进行查看并可能进行改进的原因。

//The following code is in my keyPressed function
cheatBuffer = (char)key + cheatBuffer;
cheatBuffer.resize(12);
string tempBuffer;
string cheats[3] = {"1taehc","2taehc","3taehc"};
for(int i = 0;i < 3;i++){
    tempBuffer = cheatBuffer;
    tempBuffer.resize(cheats[i].size());
    if(cheats[i] == tempBuffer){
        switch(i){
            case 1:
                //activate cheat 1
                break;
            case 2:
                //active cheat 2
                break;
            case 3:
                //active cheat 3
                break;
        }
    }
}

代码分别为“cheat1”、“cheat2”和“cheat3”。我不禁想到这可能会好很多。任何见解将不胜感激。

最佳答案

您可能要考虑使用:

std::map<std::string, std::function<void ()>> (如果你可以使用C++0x)

std::map<std::string, std::tr1::function<void ()>> (如果可以使用TR1)

std::map<std::string, boost::function<void ()>> (如果你可以使用 Boost)

(当然,函数的签名可以不同)

使用 C++0x 的例子

#include <map>
#include <functional>
#include <string>
#include <iostream>

typedef std::map<std::string, std::function<void ()>> cheat_map;

inline void cheat1()
{
    std::cout << "cheat 1 used!" << std::endl;
}

inline void cheat2()
{
    std::cout << "cheat 2 used!" << std::endl;
}

int main()
{
    cheat_map myCheats;
    myCheats.insert(std::pair<std::string, std::function<void ()>>("cheat1", std::function<void ()>(cheat1)));
    myCheats.insert(std::pair<std::string, std::function<void ()>>("cheat2", std::function<void ()>(cheat2)));

    std::string buffer;
    while (std::getline(std::cin, buffer)) {
        if (!std::cin.good()) {
            break;
        }

        cheat_map::iterator itr = myCheats.find(buffer);
        if (itr != myCheats.end()) {
            myCheats[buffer]();
        }
    }
}

输入:

notourcheat
cheat1
cheat2
cheat1

输出:

cheat 1 used!
cheat 2 used!
cheat 1 used!

Live demo

关于c++ - 有没有更优雅的方法来实现 C++ 游戏的 "cheat code"实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4651959/

相关文章:

c++ - 编译 MPI 时出错

c++ - 为什么整数到字符串的转换直到现在才明确包含在 C++ 中?

java - 将 "throw new exception"提取到方法中会导致编译错误

php - 在 PHP 中重构 if 语句或 if 语句的其他解决方案(不是 switch case)

javascript - 如何用promise避免 'callback hell'?

c++ - 在重载 =operator 中返回引用的目的是什么

c++ - 如何将可用本地接口(interface)的所有地址输出到控制台?

c++ - Cygwin 上的 Gearman : 'va_list' has not been declared

java - 什么时候在java中使用null?

php - 我应该使用框架还是编写自己的 MVC?