using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace Turtle { public class Canvas : IDisposable { protected int angle; public Bitmap Bitmap { get; protected set; } public Image Image { get; protected set; } public static readonly Pen TurtlePen = Pens.Black; public Point Position { get; set; } public int Angle { get { return angle; } set { angle = value; angle %= 360; if (angle < 0) { angle += 360; } } } public bool PenState { 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; PenState = false; } public void Dispose() { Bitmap.Dispose(); Image.Dispose(); } public void Execute(string name, int arg) { switch (name) { case "left": Angle -= arg; break; case "right": Angle += arg; break; case "pen": PenState = arg > 0; break; case "forward": if (MaxStepCount != 0 && MaxStepCount < StepCount + 1) { break; } if (PenState) { StepCount++; } using (Graphics graphics = Graphics.FromImage(Image)) { Point current = Position; Point next = current; /*double angle = Convert.ToDouble(Angle); double radAngle = angle * Math.PI / 180; if (angle < 90) { next.X += Convert.ToInt32(Math.Sin(radAngle) * arg); next.Y += Convert.ToInt32(Math.Cos(radAngle) * arg); } else if (angle < 180) { next.X += Convert.ToInt32(Math.Sin(radAngle) * arg); next.Y -= Convert.ToInt32(Math.Cos(radAngle) * arg); } else if (angle < 270) { next.X -= Convert.ToInt32(Math.Sin(radAngle) * arg); next.Y -= Convert.ToInt32(Math.Cos(radAngle) * arg); } else { next.X -= Convert.ToInt32(Math.Sin(radAngle) * arg); next.Y += Convert.ToInt32(Math.Cos(radAngle) * arg); }*/ switch (angle) { case 0: next.Y -= arg; break; case 90: next.X += arg; break; case 180: next.Y += arg; break; case 270: next.X -= arg; break; } if (PenState) { graphics.DrawLine(TurtlePen, current, next); } Position = next; } break; } } } }