Skip to main content
标签ad报错:该广告ID(9)不存在。
  主页 > Qt入门

一个qt/c++ demo,用于显示 Pentaplexity(五向复杂图案) 分形图

2023-04-24 浏览:
标签ad报错:该广告ID(7)不存在。

#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QPen>
#include <stack>

// L-System 参数
const QString axiom = "F++F++F++F++F";
const QString rule1 = "F+F++F+F";
const QString rule2 = "F-F--F-F";

// 将字符串转化为绘制指令序列
QString convertToInstructions(QString str)
{
    QString result;

    for (int i = 0; i < str.length(); ++i) {
        QChar ch = str[i];
        if (ch == 'F') { // 画线段
            result += "F";
        } else if (ch == '+') { // 右旋转
            result += "+";
        } else if (ch == '-') { // 左旋转
            result += "-";
        }
    }

    return result;
}

// 执行绘制指令
void executeInstructions(QGraphicsScene &scene, const QString &instructions)
{
    QPen pen;
    pen.setColor(Qt::GlobalColor::magenta); // 设置颜色

    double x = scene.width() / 2.0;
    double y = scene.height() / 2.0;
    double angle = M_PI / 2.0;

    std::stack<double> stackX; // 记录之前点的x坐标
    std::stack<double> stackY; // 记录之前点的y坐标
    std::stack<double> stackAngle; // 记录之前点的角度

    for (int i = 0; i < instructions.length(); ++i) {
        QChar ch = instructions[i];
        if (ch == 'F') { // 画线段
            double newX = x + qCos(angle);
            double newY = y - qSin(angle);
            scene.addLine(x, y, newX, newY, pen);
            x = newX;
            y = newY;
        } else if (ch == '+') { // 右旋转
            angle += M_PI / 5.0;
        } else if (ch == '-') { // 左旋转
            angle -= M_PI / 5.0;
        } else if (ch == '[') { // 记录之前点的状态
            stackX.push(x);
            stackY.push(y);
            stackAngle.push(angle);
        } else if (ch == ']') { // 恢复之前点的状态
            x = stackX.top();
            y = stackY.top();
            angle = stackAngle.top();
            stackX.pop();
            stackY.pop();
            stackAngle.pop();
        }
    }
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QGraphicsScene scene;
    QGraphicsView view(&scene);

    QString str = axiom;
    for (int i = 0; i < 3; ++i) {
        QString newStr;
        for (int j = 0; j < str.length(); ++j) {
            QChar ch = str[j];
            if (ch == 'F') {
                newStr += rule1;
            } else {
                newStr += ch;
            }
        }
        str = newStr;
    }
    for (int i = 0; i < 2; ++i) {
        QString newStr;
        for (int j = 0; j < str.length(); ++j) {
            QChar ch = str[j];
            if (ch == 'F') {
                newStr += rule2;
            } else {
                newStr += ch;
            }
        }
        str = newStr;
    }
    QString instructions = convertToInstructions(str);
    executeInstructions(scene, instructions);

    view.show();

    return app.exec();
}