Sunday, November 21, 2010

Trees builder

Hello world!
Suddenly I’ve decided to make the simple trees builder.
No sooner said than done.

You can see result in the image below.


Every time the algorithm generates a new tree.
After some variations variables, I found the results' similarity with the real species of trees.

[Show / hide source code]
//------------------------------------------------------------------------------
// Build a new tree
//------------------------------------------------------------------------------
void BuildTree(Point startPoint, Point endPoint, int k)
{
    Random rnd = new Random((int)DateTime.Now.Ticks);
    Pen pen = new Pen(Color.Black, k);

    if (hasLeaves)
    {
        // set the color to rnd green and width = 5 for last branch as for a leaf
        if (k < 1) pen = new Pen(Color.FromArgb(0, rnd.Next(80, 160), 0), 5);
    }

    m_Graphics.DrawLine(pen, startPoint, endPoint);

    if (k > 0)
    {
        Point pNext = new Point();
     
        // add branch to the right
        pNext = new Point(endPoint.X + rnd.Next(0, spread), endPoint.Y - rnd.Next(0, speed));
        BuildTree(endPoint, pNext, k - 1);
     
        // add branch to the left
        pNext = new Point(endPoint.X - rnd.Next(0, spread), endPoint.Y - rnd.Next(0, speed));
        BuildTree(endPoint, pNext, k - 1);

        Application.DoEvents();
    }
}

* This source code was highlighted with Source Code Highlighter.

No comments:

Post a Comment