1. 程式人生 > >C#遞迴演算法使用案例——畫樹

C#遞迴演算法使用案例——畫樹

效果圖:

部分程式碼:

private void drawTree(int n, double x0, double y0, double leng, double th)
        {
            if (n == 0) return;
            double x1 = x0 + leng * Math.Cos(th);
            double y1 = y0 + leng * Math.Sin(th);
            drawLine(x0, y0, x1, y1);

            drawTree(n - 1, x1, y1, per1 * leng * (0.5 + ran()), th + th1 * (0.5 + ran()));
            drawTree(n - 1, x1, y1, per2 * leng * (0.4 + ran()), th - th2 * (0.5 + ran()));
            if (ran() > 0.6)
                drawTree(n - 1, x1, y1, per2 * leng * (0.4 + ran()), th - th2 * (0.5 + ran()));
        }

        private void drawLine(double x0, double y0, double x1, double y1)
        {
            graphics.DrawLine(Pens.Blue, (int)x0, (int)y0, (int)x1, (int)y1);
        }

原始碼地址: