paython裡有個庫,叫turtle,俗稱海龜作圖。自己看《程式設計師的數學》時,在遞迴章節看了用海龜繪圖畫遞迴樹,我想用C#在winform上用gdi+去實現,我卻沒有在網上找到有適合C#語言的類似的庫,我就自己簡單寫了一個海龜作圖幫助類,實現了上圖的圖案。程式碼如下:
public class TurtleHelper : IDisposable { private Graphics g; private int len = 30; private int curDegree = 0; public int degree = 15; private Point curPos; private Pen pen =null; private Stack<Point> stPoints; public TurtleHelper(Graphics g, Point basePoint) { this.g = g; this.curPos = basePoint; pen = Pens.Black; stPoints = new Stack<Point>(); } public void left() { this.curDegree += this.degree; } public void right() { this.curDegree -= this.degree; } public void forward() { stPoints.Push(curPos); Point nextPoint = default; nextPoint.X =(int) (curPos.X - Math.Sin(curDegree/180.0 * Math.PI) * this.len); nextPoint.Y = (int)(curPos.Y - Math.Cos(curDegree / 180.0 * Math.PI) * this.len); this.g.DrawLine(pen, curPos, nextPoint); curPos = nextPoint; } public void back() { if(stPoints.Count>0) { var p = stPoints.Pop(); curPos = p; } } public void Dispose() { g.Dispose(); } }
三角函式,度數需要換算成弧度值,以上實現了海龜作圖的基本方法,然後在窗體畫遞迴樹的程式碼:
TurtleHelper helper = null; protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); helper = new TurtleHelper(e.Graphics, new Point(350, 350)); drawtree(7); helper.Dispose(); } public void drawtree(int n) { if(n==0||helper==null) { return; } else { helper.left(); helper.forward(); drawtree(n - 1); helper.back(); helper.right(); helper.right(); helper.forward(); drawtree(n - 1); helper.back(); helper.left(); } }