有没有更优雅的方法来实现C++游戏的"作弊代码"实现?

Sam*_*152 1 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

代码分别是"cheat1","cheat2"和"cheat3".我不禁想到这可能会好得多.任何见解将不胜感激.

Pal*_*mik 5

您可能需要考虑使用:

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]();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输入:

notourcheat
cheat1
cheat2
cheat1
Run Code Online (Sandbox Code Playgroud)

输出:

cheat 1 used!
cheat 2 used!
cheat 1 used!
Run Code Online (Sandbox Code Playgroud)

现场演示