Slavik9510

Untitled

Oct 13th, 2023
702
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <QApplication>
  2. #include <QMainWindow>
  3. #include <QGraphicsScene>
  4. #include <QGraphicsView>
  5. #include <QGraphicsLineItem>
  6. #include <QPointF>
  7. #include <cmath>
  8.  
  9. // Функція для обертання точки навколо іншої точки на певний кут
  10. QPointF rotatePoint(const QPointF& center, const QPointF& point, qreal angle) {
  11.     qreal s = sin(angle * M_PI / 180);
  12.     qreal c = cos(angle * M_PI / 180);
  13.  
  14.     qreal x = point.x() - center.x();
  15.     qreal y = point.y() - center.y();
  16.  
  17.     qreal new_x = x * c - y * s;
  18.     qreal new_y = x * s + y * c;
  19.  
  20.     new_x += center.x();
  21.     new_y += center.y();
  22.  
  23.     return QPointF(new_x, new_y);
  24. }
  25.  
  26. // Функція для малювання фрактала Коха
  27. void drawKochFractal(QGraphicsScene* scene, QPointF p1, QPointF p2, int depth, int ratio) {
  28.     if (depth == 0) {
  29.         scene->addLine(QLineF(p1, p2));
  30.     } else {
  31.         QPointF p3 = p1 + (p2 - p1) / ratio;
  32.         QPointF p4 = p1 + (p2 - p1) / ratio * 2;
  33.         QPointF p5 = rotatePoint(p3, p4, 60);
  34.  
  35.         drawKochFractal(scene, p1, p3, depth - 1, ratio);
  36.         drawKochFractal(scene, p3, p5, depth - 1, ratio);
  37.         drawKochFractal(scene, p5, p4, depth - 1, ratio);
  38.         drawKochFractal(scene, p4, p2, depth - 1, ratio);
  39.     }
  40. }
  41.  
  42. int main(int argc, char *argv[]) {
  43.     QApplication app(argc, argv);
  44.  
  45.     QMainWindow mainWindow;
  46.     QGraphicsScene scene;
  47.     QGraphicsView view(&scene);
  48.     mainWindow.setCentralWidget(&view);
  49.     mainWindow.show();
  50.  
  51.     // Початкові точки квадрата
  52.     QPointF p1(100, 100);
  53.     QPointF p2(300, 100);
  54.     QPointF p3(300, 300);
  55.     QPointF p4(100, 300);
  56.  
  57.     int iter = 4;
  58.     int ratio = 4;
  59.     // Рекурсивно малюємо фрактал Коха
  60.     drawKochFractal(&scene, p1, p2, iter, ratio);
  61.     drawKochFractal(&scene, p2, p3, iter, ratio);
  62.     drawKochFractal(&scene, p3, p4, iter, ratio);
  63.     drawKochFractal(&scene, p4, p1, iter, ratio);
  64.  
  65.     return app.exec();
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment