using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace Turtle { public class Canvas : IDisposable { protected int angle; protected Pen turtlePen = (Pen)Pens.Black.Clone(); public Bitmap Bitmap { get; protected set; } public Image Image { get; protected set; } public Point Position { get; set; } public int Angle { get { return angle; } set { angle = value; angle %= 360; if (angle < 0) { angle += 360; } } } public int PenSize { get; set; } public int StepCount { get; set; } public int MaxStepCount { get; set; } public Canvas() { // initialize bitmap Bitmap = new Bitmap(700, 700); Image = Image.FromHbitmap(Bitmap.GetHbitmap()); using (Graphics graphics = Graphics.FromImage(Image)) { graphics.FillRectangle(Brushes.White, new Rectangle(0, 0, 700, 700)); } // initialize state Position = new Point(350, 350); Angle = 0; PenSize = 0; } public void Dispose() { Bitmap.Dispose(); Image.Dispose(); } public void Execute(string name, List args) { switch (name) { case "left": Angle -= args[0]; break; case "right": Angle += args[0]; break; case "pen": PenSize = args[0]; break; case "forward": #region forward if (MaxStepCount != 0 && MaxStepCount < StepCount + 1) { break; } if (PenSize > 0) { StepCount++; } using (Graphics graphics = Graphics.FromImage(Image)) { Point current = Position; Point next = current; double angle = Convert.ToDouble(Angle); double radAngle = angle * Math.PI / 180; next.X += Convert.ToInt32(Math.Sin(radAngle) * args[0]); next.Y -= Convert.ToInt32(Math.Cos(radAngle) * args[0]); if (PenSize > 0) { turtlePen.Width = PenSize; graphics.DrawLine(turtlePen, current, next); } Position = next; } #endregion break; case "color": #region color int red = Math.Min(255, Math.Max(0, args[0])); int green = Math.Min(255, Math.Max(0, args[1])); int blue = Math.Min(255, Math.Max(0, args[2])); turtlePen = new Pen(Color.FromArgb(red, green, blue)); #endregion break; } } } }