C#使用自己写的海龟绘图类绘制递归分型树
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(); } }