0

因此,我正在考虑尝试使用 sfml 用 C++ 编写俄罗斯方块游戏,并考虑如何实现该游戏,并意识到它可能是关于继承的练习。我以为我会有:

- 一个抽象基类,将代表一个 tetromino(在俄罗斯方块中形成拼图):它称为 Tetromino_Base

- 类将从基类继承以表示特定的 tetromino,因为有不同的形状,如正方形、条形......等。

- 一个名为 Tetromino 的接口类,它是用户将操作的类型。

当我走的时候,我意识到我的类接口需要访问抽象类成员,因此我为它做了一个朋友声明,但我想:这样做是个好习惯吗?在基类中做一个朋友声明你的接口类?

这是代码的主要部分:

class Tetromino;

class Tetromino_Base {
    friend class Tetromino;
public:
    virtual ~Tetromino_Base() {};
protected:
    float m_x, m_y;
    sf::Texture m_texture;
    sf::VertexArray m_vertices;

    virtual bool create(const sf::Vector2f&, const float&, //position of the object, scale of the object
    const std::string&, const sf::Vector2f&, const float&) = 0; 
    //file name for the texture, position in the texture, scale of the texture
};

class Square : public Tetromino_Base {
public:
    ~Square() {}
private:
    bool create(const sf::Vector2f&, const float&, 
    const std::string&, const sf::Vector2f&, const float&);
};

class Tetromino : public sf::Drawable {
public:
    Tetromino(int tetroCode = 0);

    bool create(const sf::Vector2f& sorigins, const float& ssc, 
    const std::string& fileName, const sf::Vector2f& torigins, const float& tsc){
        //access needed here
        return p->create(sorigins,ssc,fileName,torigins,tsc);
    }

private:
    Tetromino(Tetromino_Base* ptr) : p (ptr) {}
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const {
        //access needed here
        states.texture = &(p->m_texture);
        target.draw(p->m_vertices, states); 
    }
    Ptr<Tetromino_Base> p;
};
4

0 回答 0