[
Advertise | Submit Code | About us | Contact us | Link us
]
Go!
Membership Services
Login
Register

Home
C# General

General

C# Language

Design & Architecture

Algorithms

Database

Security

Active Directory

COM Interop

Remoting
C# Windows Forms

General

Combo and List boxes

Miscellaneous Controls

Button Controls

Edit Controls
Cutting Edge

ASP.NET 2.0

Visual Studio 2005

Windows Longhorn

SQL Server 2005
C# Multimedia and GDI+

General

DirectX

GDI+

Audio
Internet & Web

General

Images and multimedia

Database

Utilities

Security

ASP.NET Controls

Design and Architecture

Webservices
.NET

General

Design & Architecture

Algorithms

Database

Security

Active Directory

COM Interop

Remoting

ADO.NET

XML.NET

Tools

Enterprise

IDE
Visual Basic .NET

VB.NET General

VB.NET Controls
General Reading

.NET Books Review

Product Showcase

Book Chapters

Business Design & Strategy
Community

Discuss

Job Board

Discussion

CodeXchange
DeveloperLand

Advertise

Submit Code

About us

Contact us

Link us
Miscellaneous

Favorite Links

Downloads

Programming Sites

Top Stories
Regular Expressions

E-Mail

Date/Time
Home > C# Multimedia and GDI+ > GDI+
Turtle Graphics using C#
Posted by on Monday, August 23, 2004 (EST)

In this example code, I show a minimal implementation of Turtle Graphics, using C#.

This article has been viewed: 5,426 times
Technology: GDI+.

Download the sample code:    TurtleGraphics.zip [^]

As I started to read the book Fractal Horizons by Clifford A. Pickover, I thought it would be a good idea to implement the code samples from the book.  The first samples I came across where written using Turtle Graphics commands.  I remembered that the book Turtle Geometry by Harold Abelson and Andrea diSessa, had some code in the back to implement Turtle Graphics.  This little bit of code was written in Applesoft Basic.  I was about to translate this to C#, but the Appendix mentioned that more details could be found in the Chapter 3 - Vector Methods in Turtle Geometry.  In this chapter was some pseudo code written in the style of the Logo programming language.  I used the ideas in this code to create the Turtle class presented below.  The Wrox book, Professional C# came in handy when implementing the Vector class.  The code which you can download contains many of the algorithms form Turtle Geometry, which I have implemented in C#.

The Turtle class is derived from System.Windows.Forms.UserControl.

Three variables are used to maintain the state of the turtle.

private Vector2D _P = new Vector2D( 0, 0 );
private Vector2D _H = new Vector2D( 0, 1 );
private bool _PenDown = true;

_P is the position vector, and _H is the heading vector. _PenDown, keeps track of the state of the pen.

public PointF Position
{
   get { return( new PointF( (float)_P.x, (float)_P.y ) ); }
   set { _P.x = value.X; _P.y = value.Y; }
}

The Position property returns or sets the Position vector using a PointF structure.

public bool PenDown
{
   get { return( _PenDown ); }
   set { _PenDown = value; }
}

Use the PenDown property to control or read the state of the pen.

public void Erase()
{
   Graphics g = CreateGraphics();
   Rectangle clientRect = this.ClientRectangle;
   Brush bkgBrush = new SolidBrush( Color.White );
   g.FillRectangle( bkgBrush, clientRect );
   bkgBrush.Dispose();
   g.Dispose();
   _H.x = 0;
   _H.y = 1;
   _P.x = 0;
   _P.y = 0;
}

The Erase function is used to wipe the canvas clean and initialize the Heading and Position vectors.  The heading vector is initialized to a unit vector pointing up, and the position is moved to the canvas origin.

public void GoForward( double distance )
{
   //Thread.Sleep( 100 );
   Vector2D P = new Vector2D( _P + distance * _H );
   if( _PenDown )
   {
      Graphics g = CreateGraphics();
      Matrix myMatrix = new Matrix(1, 0, 0, -1, 0, 0);
      g.Transform = myMatrix;
      g.TranslateTransform( 0, Height - 1, MatrixOrder.Append );
      g.DrawLine( new Pen( new SolidBrush( Color.Blue ), 1 ),
      new PointF( (float)_P.x, (float)_P.y ),
      new PointF( (float)P.x, (float)P.y ) );
      g.Dispose();
   }
   _P = P;
}

The GoForward function is used to update the position of the turtle.  If the pen is in the down state a line is drawn from the previous position to the current position.  A transformation matrix is use to mirror coordinates around the x-axis, giving us up as the positive y direction.  A Translate Transform is used to move the origin to the bottom left corner.

There are a number of problems with this routine, put the purpose for this code was to try out some Turtle Graphics routines.  For example, the code is called for every line which is drawn.  A more efficient way, would be to store the lines in a Path object and draw them all at once.  Also there is no code here for saving the drawing information, and performing a re-draw during an OnPaint.  An example of how this can be done, can be found in the code for the Drawing Canvas example.

public void GoBack( double distance )
{
   GoForward( -1.0 * distance );
}

public void GoLeft( double angle )
{
   _H = Rotate( _H, angle );
}

public void GoRight( double angle )
{
   GoLeft( -1.0 * angle );
}

The GoForward, GoBack, GoLeft, & GoRight functions are a minimal implementation of the Turtle Graphics language.  This is all that is needed, because everything else can easily be written in C#, as demonstrated in the examples in the Art class.

private Vector2D Rotate( Vector2D V, double angle )
{
   return( Math.Cos( angle * Math.PI / 180.0 ) * V
      + Math.Sin( angle * Math.PI / 180.0 ) * Perp( V ) );
}

private Vector2D Perp( Vector2D V )
{
   return( new Vector2D( -1.0 * V.y, V.x ) );
}

The Rotate & Perp functions are use to translate turtle rotation angles into changes in the Heading vector.

public class Vector2D
{
   public double x;
   public double y;

public Vector2D( double vx, double vy )
{
   x = vx;
   y = vy;
}

public Vector2D( Vector2D v )
{
   x = v.x;
   y = v.y;
}

public static Vector2D operator + ( Vector2D lhs, Vector2D rhs )
{
   Vector2D result = new Vector2D( lhs );
   result.x += rhs.x;
   result.y += rhs.y;
   return( result );
}

public static Vector2D operator * ( double lhs, Vector2D rhs )
{
   Vector2D result = new Vector2D( rhs );
   result.x *= lhs;
   result.y *= lhs;
   return( result );
}

public static Vector2D operator * ( Vector2D lhs, double rhs )
{
   Vector2D result = new Vector2D( lhs );
   result.x *= rhs;
   result.y *= rhs;
   return( result );
}

To see the sample code in action, create a C# Windows application and add the downloaded code to it. Click the entries in the list box to see the corresponding drawing on the Turtle control on the right. Examine the code in the Art class to see the Turtle graphics algorithms used to create the drawings.

Top Go to Table of Contents

About Bill Burris

3D Graphics, OpenGL AI Python, C#, C++

Click here if you want to know more about .

Other articles that may interest you

  • Write a Word Add-In – Part 0
  • Write a Word Add-In – Part I
  • Lengthy Operations on Single Thread in .NET Application
  • Learning Draughts
  • Exceptions and Performance
  • Average Rating :

    Discussion Forums
    Got a programming related question? Hopefully someone has the answer... Want to help out other developers? Visit our discussion forums.

    Sponsored by:

    New Articles

  • Exceptions and Performance
    Almost every time exceptions are mentioned in mailing lists and newsgroups, people say they're really expensive.Let's examine that claim, shall we?

  • Creating multilingual websites - Part 1
    Extend the existing globalization capabilities of .NET to create flexible and powerful multilingual web sites. First, create a custom ResourceManager, and then create custom localized-capable server controls to easily deploy multilingual functionality.

  • Parameter passing in C#
    Many people have become fairly confused about how parameters are passed in C#, particularly with regard to reference types. This page should help to clear up some of that confusion

  • Most Popular Articles

  • LDAP, IIS and WinNT Directory Services
    This article explains how to use .NET Directory Services to retrieve and search directory objects, create new directory objects and edit or delete existing directory objects. Describes Active Directory Application Mode (ADAM) and how to use the IIS, WinNT and LDAP directory (ADSI) provider.

  • An in-depth look at WMI and instrumentation, Part II
    WMI stands for Windows Management Instrumentation and, as the name indicates, is about managing your IT infrastructure this article is the second part of a two-part series.

  • An in-depth look at WMI and instrumentation, Part I
    WMI stands for Windows Management Instrumentation and, as the name indicates, is about managing your IT infrastructure this article provides an in-depth look at WMI and MOM 2005

  • New Books

  • Murach's ASP.NET 2.0 Upgrader's Guide: VB Edition
    What’s new and how to use it! That’s what this book delivers if you’re a VB developer who’s interested in upgrading from ASP.NET 1.x to ASP.NET 2.0.

  • C# in easy steps
    Learn to program with Microsoft’s premier programming language. No previous programming knowledge is assumed. With numerous easy-to-follow examples, this title explains the essentials of object-oriented programming with C#.

  • Murach's ASP.NET web programming with VB.NET
    Murach's ASP.NET web programming with VB.NET by Doug Lowe and Anne Prince is a in depth training and reference book for ASP.NET programming using VB.NET. The book builds upon Murach's previous books and covers more advanced concepts for programming ASP.NET pages.

  • Got Code?

    if you have any article , source code , or anything else you'd like to share with this community that you think others might find useful, please submit it here and we will gladly make it available on this site. submit@developerland.com.
    Partners

    All articles are copyrighted by their individual authors unless otherwise specified , everything else Copyright ©2004-2006 DeveloperLand