如何在 C++ 中建造类似于 Scratch 的舞台?

· · 科技·工程

引入一个蜜汁疑问:如何在 C++ 中建造类似于 Scratch 的舞台?

我查了一些资料,写一篇 Blog。

另外,身为一个 OIer,为什么会问和研究这种问题啊?!

理论

在 C++ 中,想生成一个窗口(舞台)需要依赖第三方图形库。相对轻量的 SFML(Simple and Fast Multimedia Library)是一个不错的选择。这个图形库可以创建可视化窗口与元素或角色。

理论存在,实践开始。

让我们举起🌰——

实例 A

目标🎯:把一个绿色的矩形作为角色,通过上下左右键控制它移动。

实现思路

int main() { sf::RenderWindow w(sf::VideoMode(800,600),"Window Name"); sf::RectangleShape c(sf::Vector2f(50,50)); c.setFillColor(sf::Color::Green); c.setPosition(375,275); while(w.isOpen()) { sf::Event e; while(w.pollEvent(e)) { // 当用户关闭窗口时,退出循环 if(e.type==sf::Event::Closed) w.close(); // 键盘事件 if(e.type==sf::Event::KeyPressed) { if(e.key.code==sf::Keyboard::Left) c.move(-10,0); else if(e.key.code==sf::Keyboard::Right) c.move(10,0); else if(e.key.code==sf::Keyboard::Up) c.move(0,-10); else if(e.key.code==sf::Keyboard::Down) c.move(0,10); } } // 清屏 w.clear(sf::Color::White); // 绘制角色 w.draw(c); // 显示窗口内容 w.display(); } }

### 实例 B
目标🎯:在上述基础上实现角色间的碰撞检测。
#### 实现思路
- 同实例 A,我们需要创建窗口、绘制元素(角色)、处理事件、更新渲染。
- 碰撞检测:写一个 `isColliding()` 方法,使用 `intersects()` 方法。
- 角色移动:键盘事件和鼠标事件。
#### 代码实现
```cpp
#include<SFML/Graphics.hpp>
#include<bits/stdc++.h>

class C // 元素(角色)类
{
public:
    sf::RectangleShape s; // 元素(角色)
    sf::Vector2f v; // 速度
    sf:Clock c; // 动画帧
    int cF=0; // 动画帧——切换帧
    std::vector<sf::IntRect> F; // 存储帧信息
    C(float x,float y,float w,float h) // 构造函数
    {
        s.setSize(sf::Vector2f(w,h));
        s.setPosition(x,y);
        s.setFillColor(sf::Color::Blue);
        for(int i=0;i<4;i++) // 设置动画帧
            F.emplace_back(i*w,0,w,h);
    }
    void update() // 更新状态的方法
    {
        s.move(v);
        if(c.getElapsedTime().asSeconds()>0.1)
            {cF=(cF+1)%(int)(F.size());c.restart();}
    }
    bool isColliding(const C& other) const // 检测碰撞的方法
    {
        return s.getGlobalBounds().intersects(other.s.getGlobalBounds());
    }
};

int main()
{
    sf::RenderWindow w(sf::VideoMode(800,600),"Window Name");
    C c1(100,100,50,50);
    C c2(300,300,50,50);
    std::vector<C> cs(c1,c2);
    while(w.isOpen())
    {
        sf::Event e;
        while(w.pollEvent(e))
        {
            if(e.type==sf::Event.Closed)
                w.close();
            // 键盘控制c1
            if(e.type==sf::Event::KeyPressed)
            {
                if(e.key.code==sf::Keyboard::Left)
                    cs[0].v.x=-5;
                else if(e.key.code==sf::Keyboard::Right)
                    cs[0].v.x=5;
                else if(e.key.code==sf::Keyboard::Up)
                    cs[0].v.y=-5;
                else if(e.key.code==sf::Keyboard::Down)
                    cs[0].v.y=5;
            }
            if(e.type==sf::Event::KeyReleased)
            {
                if(e.key.code==sf::Keyboard::Left||e.key.code==sf::Keyboard::Right)
                    cs[0].v.x=0;
                else if(e.key.code==sf::Keyboard::Up||e.key.code == sf::Keyboard::Down)
                    cs[0].v.y=0;
            }
            // 鼠标点击控制c2移动到点击位置
            if(e.type==sf::Event::MouseButtonPressed)
            {
                if(e.mouseButton.button==sf::Mouse::Left)
                {
                    sf::Vector2i mP=sf::Mouse::getPosition(w);
                    sf::Vector2f targetPos(mP.x,mP.y);
                    sf::Vector2f d=targetPos-cs[1].s.getPosition();
                    float len=std::sqrt(d.x*d.x+d.y*d.y);
                    if(len>0)
                        cs[1].v=d/len*5.f;
                }
            }
        }
        // 更新状态
        for(auto& cc:cs) cc.update();
        // 碰撞检测——碰到就变红
        if(cs[0].isColliding(cs[1]))
        {
            cs[0].s.setFillColor(sf::Color::Red);
            cs[1].s.setFillColor(sf::Color::Red);
        }
        else
        {
            cs[0].s.setFillColor(sf::Color::Blue);
            cs[1].s.setFillColor(sf::Color::Blue);
        }
        // 清屏
        w.clear(sf::Color::White);
        // 绘制角色
        for(const auto& cc:cs) w.draw(cc.s);
        // 显示窗口内容
        w.display();
    }
}

总结

想在 C++ 中实现类似于 Scratch 的舞台,可以使用第三方图形库 SFML,但需要先从官网下载。

正如 C++ 之父 Bjarne Stroustrup 所言,优化 C++ 是使其在自己擅长的方面做得更好,而不是将 C++ 扩展到其不擅长的新领域。因此,像舞台这样的功能,我们最好还是交给 Python 和 Scratch 吧!