Blog url: https://wysaid.org/570.html
无聊一水,零优化画了个koch。贴下:
贴代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
/* Author: wysaid * Title: Koch Line * Blog: https://wysaid.org/ * Date:2013-6-6 */ #include <graphics.h> #include <vector> #include <cmath> #define PI 3.14159f #define PI2 (2*PI) #define FLOATCOMP0(x) (x < 0.01f && x > -0.01f) using std::vector; const float g_sqrt3 = sqrtf(3.0f); const float g_angle = PI / 6.0f; float getAngleByNormal(float x, float y) { float d = sqrtf(x*x+y*y); if(FLOATCOMP0(d)) return .0f; float angle = asinf(y / d); if(x > .0f) { if(y > .0f) return angle; else return PI2 + angle; } else { return PI - angle; } } struct Point { Point(){} Point(float a, float b):x(a), y(b) {} float x, y; Point kochNewPoint(Point& p) { float dis = (p-*this).normalSize(); float disP = dis / g_sqrt3; float angle = getAngleByNormal(p.x - x, p.y - y) + g_angle; return Point(x + disP * cos(angle), y + disP*sin(angle)); } float normalSize() { return sqrtf(x*x+y*y); } Point operator+(Point& p) { return Point(x+p.x, y+p.y); } Point operator-(Point& p) { return Point(x - p.x, y - p.y); } Point operator*(float f) { return Point(x * f, y * f); } }; vector<Point> g_vp; void drawFractal(Point a, Point b, int n) { vector<Point> tmp; g_vp.clear(); g_vp.push_back(a); g_vp.push_back(b); while(n--) { std::vector<Point>::iterator iter = g_vp.begin(); for(tmp.push_back(*iter++); iter < g_vp.end(); ++iter) { Point m, n; m = iter[-1]; n = *iter; Point normal = m+n; tmp.push_back(m + (n-m)*(1.0f/3.0f)); tmp.push_back(m.kochNewPoint(n)); tmp.push_back(m + (n-m)*(2.0f/3.0f)); tmp.push_back(n); } g_vp = tmp; tmp.clear(); } std::vector<Point>::iterator i = g_vp.begin(); moveto(i->x, i->y); for(++i; i < g_vp.end(); ++i) { setcolor(random(0x7fffff) + 0x700000); lineto(i->x, i->y); } } int main() { Point a(40, 240), b(600, 240); initgraph(640, 480); int n = 0; while(1) { cleardevice(); drawFractal(a, b, n); getch(); flushkey(); ++n; } closegraph(); return 0; } |
使用vs2008以及EGE13.04 编译运行通过。如果没有EGE,点击此处
我能不能来水一贴…..