更好的设计模式,用于读取其他进程内存?

时间:2016-08-01 19:44:27

标签: c++

我正在为一个离线游戏写一个作弊,并且有一个名为Player的类,它负责在另一个进程中获取和设置值。但是,我对这个类的设计非常差,因为类Player的使用看起来非常混乱和难看,很难阅读和维护

// declare variables here to read
if (Player.getthis() && Player.getthat() && Player.getthat() ... and so on) 
//do stuff

class Player {
...
public:
    ...
    // either of these calls can fail, so I return TRUE on success and FALSE on failure
    BOOL GetHealth(float& health);
    BOOL SetHealth(float& health);  
    ...
};

所以我的问题是,有什么更好的方法呢? 另外:我不一定需要在内存中读取Player的每个值,一次只读几个。这就是为什么我没有一个方法,如BOOL UpdatePlayer(),它将读取所有内容并更新播放器

1 个答案:

答案 0 :(得分:1)

我将如何做到这一点:

class Player {
public:
    class AccessException : public std::exception {
        friend class Player;
    public:
        virtual const char *what() const noexcept {
            return "Error getting property with key " + key;
        }

    private:
        AccessException(const std::string &key)
            : key(key)
        {}

        std::string key;
    };

    float GetHealth() {
        if (is_error) {
            throw AccessException("health");
        }

        return health;
    }

    float GetPosX() {
        if (is_error) {
            throw AccessException("posX");
        }

        return posX;
    }
};

void do_stuff() {
    try {
        float health = player.GetHealth();
        float posX = player.GetPosX();
        // Use health and posX...
    } catch (const AccessException &ex) {
        std::cerr << ex.what() << std::endl;
    }
}