diff --git a/ProjectDumpTruck/DirectionType.cs b/ProjectDumpTruck/DirectionType.cs new file mode 100644 index 0000000..d555ecb --- /dev/null +++ b/ProjectDumpTruck/DirectionType.cs @@ -0,0 +1,8 @@ +using System; + +public class Class1 +{ + public Class1() + { + } +} diff --git a/ProjectDumpTruck/DrawningDumpTrack.cs b/ProjectDumpTruck/DrawningDumpTrack.cs new file mode 100644 index 0000000..d555ecb --- /dev/null +++ b/ProjectDumpTruck/DrawningDumpTrack.cs @@ -0,0 +1,8 @@ +using System; + +public class Class1 +{ + public Class1() + { + } +} diff --git a/ProjectDumpTruck/DrawningTrack.cs b/ProjectDumpTruck/DrawningTrack.cs new file mode 100644 index 0000000..d555ecb --- /dev/null +++ b/ProjectDumpTruck/DrawningTrack.cs @@ -0,0 +1,8 @@ +using System; + +public class Class1 +{ + public Class1() + { + } +} diff --git a/ProjectDumpTruck/EntityDampTrack.cs b/ProjectDumpTruck/EntityDampTrack.cs new file mode 100644 index 0000000..d555ecb --- /dev/null +++ b/ProjectDumpTruck/EntityDampTrack.cs @@ -0,0 +1,8 @@ +using System; + +public class Class1 +{ + public Class1() + { + } +} diff --git a/ProjectDumpTruck/EntityTrack.cs b/ProjectDumpTruck/EntityTrack.cs new file mode 100644 index 0000000..d555ecb --- /dev/null +++ b/ProjectDumpTruck/EntityTrack.cs @@ -0,0 +1,8 @@ +using System; + +public class Class1 +{ + public Class1() + { + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DirectionType.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DirectionType.cs new file mode 100644 index 0000000..4362338 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DirectionType.cs @@ -0,0 +1,35 @@ +namespace ProjectDumpTrack.Drawnings; + +/// +/// Направление перемещения +/// +public enum DirectionType +{ + /// + /// Неизвестное направление + /// + Unknow = -1, + + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 + + +} + diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningDumpTrack.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningDumpTrack.cs new file mode 100644 index 0000000..cc9e727 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningDumpTrack.cs @@ -0,0 +1,106 @@ +using ProjectDumpTrack.Entities; + +namespace ProjectDumpTrack.Drawnings; +/// +/// Класс, отвечающий за прорисовку и перемещение объекта-сущности +/// +public class DrawningDumpTrack : DrawningTrack +{ + ////2 задание + //public override bool MoveTransport(DirectionType direction) + //{ + // if (EntityTrack == null || !_startPosX.HasValue || !_startPosY.HasValue) + // { + // return false; + // } + + // switch (direction) + // { + // //влево + // case DirectionType.Left: + // if (_startPosX.Value - EntityTrack.Step > 0) + // { + // _startPosX -= (int)EntityTrack.Step; + // } + // return true; + + // //вверх + // case DirectionType.Up: + // if (_startPosY.Value - EntityTrack.Step > 0) + // { + // _startPosY -= (int)EntityTrack.Step; + // } + // return true; + + // //вправо + // case DirectionType.Right: + // if (_startPosX.Value + EntityTrack.Step + _drawningTrackWidth < _pictureWidth) + // { + // _startPosX += (int)EntityTrack.Step; + // } + // return true; + + // //вниз + // case DirectionType.Down: + // if (_startPosY.Value + EntityTrack.Step + _drawningTrackHeight < _pictureHeight) + // { + // _startPosY += (int)EntityTrack.Step; + // } + // return true; + // default: + // return false; + // } + + //} + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия кузова + /// Признак наличия тента + + + public DrawningDumpTrack(int speed, double weight, Color bodyColor, Color additionalColor, bool bodywork, bool awning) : base(130, 100) + { + EntityTrack = new EntityDumpTrack(speed, weight, bodyColor, additionalColor, bodywork, awning); + + } + + public override void DrawTransport(Graphics g) + { + if (EntityTrack == null || EntityTrack is not EntityDumpTrack dumpTrack || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black); + Brush additionalBrush = new SolidBrush(dumpTrack.AdditionalColor); + + base.DrawTransport(g); + + //Отрисовка кузова + if (dumpTrack.Bodywork) + { + g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value, 90, 35); + } + + //Отрисовка тента + if (dumpTrack.Bodywork & dumpTrack.Awning) + { + g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value, 95, 10); + g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value, 95, 3); + g.FillRectangle(additionalBrush, _startPosX.Value + 30, _startPosY.Value, 3, 40); + g.FillRectangle(additionalBrush, _startPosX.Value + 70, _startPosY.Value, 3, 40); + } + + + base.DrawTransport(g); + + } + +} + diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTrack.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTrack.cs new file mode 100644 index 0000000..8cc5536 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTrack.cs @@ -0,0 +1,246 @@ + +using ProjectDumpTrack.Entities; + +namespace ProjectDumpTrack.Drawnings; +public class DrawningTrack +{ + /// + /// Класс-сущность + /// + public EntityTrack? EntityTrack { get; protected set; } + + /// + /// Ширина окна + /// + private int? _pictureWidth; + + + /// + /// Высота окна + /// + private int? _pictureHeight; + + + /// + /// Левая координата прорисовки самосвала + /// + protected int? _startPosX; + + /// + /// Верхняя координата прорисовки самосвала + /// + protected int? _startPosY; + + /// + /// Ширина прорисовки самосвала + /// + private readonly int _drawningTrackWidth = 130; + + /// + /// Высота прорисовки самосвала + /// + private readonly int _drawningTrackHeight = 100; + + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningTrackWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawningTrackHeight; + + /// + /// Пустой конструктор + /// + private DrawningTrack() + { + _pictureWidth = null; + _pictureHeight = null; + _startPosX = null; + _startPosY = null; + } + + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + + + public DrawningTrack(int speed, double weight, Color bodyColor) : this() + { + EntityTrack = new EntityTrack(speed, weight, bodyColor); + + } + + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки автомобиля + /// Высота прорисовки автомобиля + + + + protected DrawningTrack(int drawningTrackWidth, int drawningTrackHeight) : this() + { + _drawningTrackWidth = drawningTrackWidth; + _drawningTrackHeight = drawningTrackHeight; + + } + + + + /// + /// Установка границ поля + /// + /// Ширина поля + /// Высота поля + /// true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах + public bool SetPictureSize(int width, int height) + { + // TODO проверка, что объект "влезает" в размеры поля + // если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена + if (_drawningTrackWidth > width || _drawningTrackHeight > height) + { + return false; + } + + _pictureWidth = width; + _pictureHeight = height; + + return true; + } + + /// + /// Установка позиции + /// + /// Координата X + /// Координата Y + public void SetPosition(int x, int y) + { + if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) + { + return; + } + // TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы + // то надо изменить координаты, чтобы он оставался в этих границах + if (x + _drawningTrackWidth > _pictureWidth) + { + x -= _drawningTrackWidth; + } + if (y + _drawningTrackHeight > _pictureHeight) + { + y -= _drawningTrackHeight; + } + if (x < 0) + { + x = 0; + } + if (y < 0) + { + y = 0; + } + + _startPosX = x; + _startPosY = y; + + + } + /// + /// Изменение направления перемещения + /// + /// Направление + /// true - перемещение выполнено, false - перемещение невозможно + public bool MoveTransport(DirectionType direction) + { + if (EntityTrack == null || !_startPosX.HasValue || !_startPosY.HasValue) + { + return false; + } + + switch (direction) + { + //влево + case DirectionType.Left: + if (_startPosX.Value - EntityTrack.Step > 0) + { + _startPosX -= (int)EntityTrack.Step; + } + return true; + + //вверх + case DirectionType.Up: + if (_startPosY.Value - EntityTrack.Step > 0) + { + _startPosY -= (int)EntityTrack.Step; + } + return true; + + //вправо + case DirectionType.Right: + if (_startPosX.Value + EntityTrack.Step + _drawningTrackWidth < _pictureWidth) + { + _startPosX += (int)EntityTrack.Step; + } + return true; + + //вниз + case DirectionType.Down: + if (_startPosY.Value + EntityTrack.Step + _drawningTrackHeight < _pictureHeight) + { + _startPosY += (int)EntityTrack.Step; + } + return true; + default: + return false; + } + + } + + public virtual void DrawTransport(Graphics g) + { + if (EntityTrack == null || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black); + + + //Отрисовка основы (кабины водителя и днища) + Brush body = new SolidBrush(EntityTrack.BodyColor); + g.FillRectangle(body, _startPosX.Value + 100, _startPosY.Value, 30, 35); + g.FillRectangle(body, _startPosX.Value, _startPosY.Value + 40, 130, 20); + + //Отрисовка колёс + Brush wheels = new SolidBrush(Color.Gray); + g.FillEllipse(wheels, _startPosX.Value, _startPosY.Value + 60, 30, 30); + g.FillEllipse(wheels, _startPosX.Value + 30, _startPosY.Value + 60, 30, 30); + g.FillEllipse(wheels, _startPosX.Value + 100, _startPosY.Value + 60, 30, 30); + + //Отрисовка границ + Brush border = new SolidBrush(Color.Black); + g.DrawRectangle(pen, _startPosX.Value + 100, _startPosY.Value, 30, 35); + g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 40, 130, 20); + g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 60, 30, 30); + g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 60, 30, 30); + g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 60, 30, 30); + + + } + +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityDumpTrack.cs b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityDumpTrack.cs new file mode 100644 index 0000000..9999843 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityDumpTrack.cs @@ -0,0 +1,47 @@ +namespace ProjectDumpTrack.Entities; + +/// +/// Класс-сущность "Самосвал" +/// +public class EntityDumpTrack : EntityTrack +{ + /// + /// Дополнительный цвет (для опциональных элементов) + /// + public Color AdditionalColor { get; private set; } + + /// + /// Признак (опция) наличия кузова + /// + public bool Bodywork { get; private set; } + + /// + /// Признак (опция) наличия тента + /// + public bool Awning { get; private set; } + + + + /// + /// Инициализация полей объекта-класса самосвала + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия кузова + /// Признак наличия тента + + public EntityDumpTrack(int speed, double weight, Color bodyColor, Color additionalColor, bool bodywork, bool awning) : base(5, 45, Color.Black) + { + AdditionalColor = additionalColor; + Bodywork = bodywork; + Awning = awning; + } + + +} + + + + diff --git a/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityTrack.cs b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityTrack.cs new file mode 100644 index 0000000..257fb9b --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/Entities/EntityTrack.cs @@ -0,0 +1,45 @@ + +namespace ProjectDumpTrack.Entities; + +/// +/// Класс-сущность "Грузовик" +/// +public class EntityTrack +{ + /// + /// Скорость + /// + public int Speed { get; private set; } + + /// + /// Вес + /// + public double Weight { get; private set; } + + /// + /// Основной цвет + /// + public Color BodyColor { get; private set; } + + /// + /// Шаг перемещения самосвала + /// + public double Step => Speed * 100 / Weight; + + /// + /// Конструктор сущности + /// + /// Скорость + /// Вес + /// Основной цвет + + + public EntityTrack(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + + } +} + diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormTransport.Designer.cs b/ProjectDumpTruck/ProjectDumpTruck/FormTransport.Designer.cs index ab23f41..5b55460 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTransport.Designer.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTransport.Designer.cs @@ -34,6 +34,9 @@ buttonRight = new Button(); buttonUp = new Button(); buttonDown = new Button(); + buttonCreateTrack = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxDumpTrack).BeginInit(); SuspendLayout(); // @@ -51,9 +54,9 @@ buttonCreateDumpTrack.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateDumpTrack.Location = new Point(12, 409); buttonCreateDumpTrack.Name = "buttonCreateDumpTrack"; - buttonCreateDumpTrack.Size = new Size(94, 29); + buttonCreateDumpTrack.Size = new Size(210, 29); buttonCreateDumpTrack.TabIndex = 1; - buttonCreateDumpTrack.Text = "Создать"; + buttonCreateDumpTrack.Text = "Создать грузовик с кузовом"; buttonCreateDumpTrack.UseVisualStyleBackColor = true; buttonCreateDumpTrack.Click += buttonCreateDumpTrack_Click; // @@ -105,11 +108,45 @@ buttonDown.UseVisualStyleBackColor = true; buttonDown.Click += buttonMove_Click; // + // buttonCreateTrack + // + buttonCreateTrack.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateTrack.Location = new Point(238, 409); + buttonCreateTrack.Name = "buttonCreateTrack"; + buttonCreateTrack.Size = new Size(210, 29); + buttonCreateTrack.TabIndex = 6; + buttonCreateTrack.Text = "Создать грузовик"; + buttonCreateTrack.UseVisualStyleBackColor = true; + buttonCreateTrack.Click += buttonCreateTrack_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(670, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(112, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(721, 41); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(61, 22); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormTransport // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(800, 450); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreateTrack); Controls.Add(buttonDown); Controls.Add(buttonUp); Controls.Add(buttonRight); @@ -130,5 +167,8 @@ internal Button buttonRight; internal Button buttonUp; internal Button buttonDown; + private Button buttonCreateTrack; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormTransport.cs b/ProjectDumpTruck/ProjectDumpTruck/FormTransport.cs index 1da4f47..e3c9f5f 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/FormTransport.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/FormTransport.cs @@ -1,4 +1,8 @@ -/// + +using ProjectDumpTrack.Drawnings; +using ProjectDumpTruck.MovementStrategy; + +/// /// Форма работы с объектом "Самосвал" /// namespace ProjectDumpTruck @@ -8,14 +12,19 @@ namespace ProjectDumpTruck /// /// Поле-объект для прорисовки объекта /// - private DrawningDumpTrack? _drawningDumpTrack; + private DrawningTrack? _drawningTrack; + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; /// /// Конструктор формы /// public FormTransport() { InitializeComponent(); + _strategy = null; } /// @@ -23,38 +32,65 @@ namespace ProjectDumpTruck /// private void Draw() { - if (_drawningDumpTrack == null) + if (_drawningTrack == null) { return; } Bitmap bmp = new(pictureBoxDumpTrack.Width, pictureBoxDumpTrack.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningDumpTrack.DrawTransport(gr); + _drawningTrack.DrawTransport(gr); pictureBoxDumpTrack.Image = bmp; + + } /// - /// Обработка нажатия кнопки "Создать" + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawningTrack): + _drawningTrack = new DrawningTrack(random.Next(100, 300), random.Next(1000, 3000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256))); + break; + case nameof(DrawningDumpTrack): + _drawningTrack = new DrawningDumpTrack(random.Next(100, 300), random.Next(1000, 3000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + Convert.ToBoolean(random.Next(1, 2)), Convert.ToBoolean(random.Next(0, 2))); + break; + default: + return; + } + + _drawningTrack.SetPictureSize(pictureBoxDumpTrack.Width, pictureBoxDumpTrack.Height); + _drawningTrack.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } + + + /// + /// Обработка нажатия кнопки "Создать грузовик с кузовом" /// /// /// - private void buttonCreateDumpTrack_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningDumpTrack = new DrawningDumpTrack(); - _drawningDumpTrack.Init(random.Next(100, 300), random.Next(1000, 3000), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); - - _drawningDumpTrack.SetPictureSize(pictureBoxDumpTrack.Width, pictureBoxDumpTrack.Height); - _drawningDumpTrack.SetPosition(random.Next(10, 100), random.Next(10, 100)); + private void buttonCreateDumpTrack_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningDumpTrack)); + + /// + /// Обработка нажатия кнопки "Создать грузовик" + /// + /// + /// + private void buttonCreateTrack_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTrack)); + - Draw(); - } - - /// /// Перемещение объекта по форме (нажатие кнопок навигации) /// @@ -62,7 +98,7 @@ namespace ProjectDumpTruck /// private void buttonMove_Click(object sender, EventArgs e) { - if (_drawningDumpTrack == null) + if (_drawningTrack == null) { return; } @@ -72,16 +108,16 @@ namespace ProjectDumpTruck switch (name) { case "buttonUp": - result = _drawningDumpTrack.MoveTransport(DirectionType.Up); + result = _drawningTrack.MoveTransport(DirectionType.Up); break; case "buttonDown": - result = _drawningDumpTrack.MoveTransport(DirectionType.Down); + result = _drawningTrack.MoveTransport(DirectionType.Down); break; case "buttonLeft": - result = _drawningDumpTrack.MoveTransport(DirectionType.Left); + result = _drawningTrack.MoveTransport(DirectionType.Left); break; case "buttonRight": - result = _drawningDumpTrack.MoveTransport(DirectionType.Right); + result = _drawningTrack.MoveTransport(DirectionType.Right); break; } if (result) @@ -89,5 +125,48 @@ namespace ProjectDumpTruck Draw(); } } + + /// + /// + /// + /// + /// + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningTrack == null) + { + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableTrack(_drawningTrack), pictureBoxDumpTrack.Width, pictureBoxDumpTrack.Height); + } + + if (_strategy == null) + { + return; + } + + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } } -} +} \ No newline at end of file diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/AbstractStrategy.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..06e3938 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,143 @@ + +namespace ProjectDumpTruck.MovementStrategy; + +/// +/// Класс-стратегия перемещения объекта +/// +public abstract class AbstractStrategy +{ + ////Абстрактный метод 3 задание + //public abstract void MyAbstractMethod(); + + /// + /// Перемещаемый объект + /// + private IMoveableObject? _moveableObject; + + /// + /// Статус перемещения + /// + private StrategyStatus _state = StrategyStatus.NotInit; + + /// + /// Ширина поля + /// + protected int FieldWidth { get; private set; } + + /// + /// Высота поля + /// + protected int FieldHeight { get; private set; } + + /// + /// Статус перемещения + /// + public StrategyStatus GetStatus() { return _state; } + + /// + /// Установка данных + /// + /// Перемещаемый объект + /// Ширина поля + /// Высота поля + public void SetData(IMoveableObject moveableObject, int width, int height) + { + if (moveableObject == null) + { + _state = StrategyStatus.NotInit; + return; + } + + _state = StrategyStatus.InProgress; + _moveableObject = moveableObject; + FieldWidth = width; + FieldHeight = height; + } + + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != StrategyStatus.InProgress) + { + return; + } + + if (IsTargetDestinaion()) + { + _state = StrategyStatus.Finish; + return; + } + + MoveToTarget(); + } + + /// + /// Перемещение влево + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveLeft() => MoveTo(MovementDirection.Left); + + /// + /// Перемещение вправо + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveRight() => MoveTo(MovementDirection.Right); + + /// + /// Перемещение вверх + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveUp() => MoveTo(MovementDirection.Up); + + /// + /// Перемещение вниз + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveDown() => MoveTo(MovementDirection.Down); + + /// + /// Параметры объекта + /// + protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition; + + /// + /// Шаг объекта + /// + /// + protected int? GetStep() + { + if (_state != StrategyStatus.InProgress) + { + return null; + } + return _moveableObject?.GetStep; + } + + /// + /// Перемещение к цели + /// + protected abstract void MoveToTarget(); + + /// + /// Достигнута ли цель + /// + /// + protected abstract bool IsTargetDestinaion(); + + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат попытки (true - удалось переместиться, false - неудача) + private bool MoveTo(MovementDirection movementDirection) + { + if (_state != StrategyStatus.InProgress) + { + return false; + } + + return _moveableObject?.TryMoveObject(movementDirection) ?? false; + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/IMoveableObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/IMoveableObjects.cs new file mode 100644 index 0000000..ab6199f --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/IMoveableObjects.cs @@ -0,0 +1,28 @@ + +namespace ProjectDumpTruck.MovementStrategy; + +/// +/// Интерфейс для работы с перемещаемым объектом +/// +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); + + ////Интерфейс - задание 1 + //void MyMethod(); +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToBorder.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..d807325 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,57 @@ + +namespace ProjectDumpTruck.MovementStrategy; + +public class MoveToBorder : AbstractStrategy +{ + ////Абстрактный метод 3 задание + //public override void MyAbstractMethod() + //{ + // Console.WriteLine("Implementation of abstract method in derived class"); + //} + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + + return objParams.RightBorder <= FieldWidth && objParams.RightBorder + GetStep() >= FieldWidth && + objParams.DownBorder <= FieldHeight && objParams.DownBorder + GetStep() >= FieldHeight; + } + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + + int diffX = objParams.RightBorder - FieldWidth; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + + int diffY = objParams.DownBorder - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } +} + diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToCenter.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..b0db1d8 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,60 @@ + +namespace ProjectDumpTruck.MovementStrategy; + +/// +/// Стратегия перемещения объекта в центр экрана +/// +public class MoveToCenter : AbstractStrategy +{ + ////Абстрактный метод 3 задание + //public override void MyAbstractMethod() + //{ + // Console.WriteLine("Implementation of abstract method in derived class"); + //} + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + + return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 && + objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2; + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + + int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + + int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveableTrack.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveableTrack.cs new file mode 100644 index 0000000..d54ce02 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MoveableTrack.cs @@ -0,0 +1,74 @@ + +using ProjectDumpTrack.Drawnings; + +namespace ProjectDumpTruck.MovementStrategy; + +/// +/// Класс-реализация IMoveableObject с использованием DrawningTrack +/// +public class MoveableTrack : IMoveableObject +{ + ////Интерфейс-задание 1 + //public void MyMethod() + //{ + + //} + + + + + /// + /// Поле-объект класса DrawningCar или его наследника + /// + private readonly DrawningTrack? _track = null; + + /// + /// Конструктор + /// + /// Объект класса DrawningCar + public MoveableTrack(DrawningTrack track) + { + _track = track; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_track == null || _track.EntityTrack == null || !_track.GetPosX.HasValue || !_track.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_track.GetPosX.Value, _track.GetPosY.Value, _track.GetWidth, _track.GetHeight); + } + } + + public int GetStep => (int)(_track?.EntityTrack?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_track == null || _track.EntityTrack == null) + { + return false; + } + + return _track.MoveTransport(GetDirectionType(direction)); + } + + /// + /// Конвертация из MovementDirection в DirectionType + /// + /// MovementDirection + /// DirectionType + private static DirectionType GetDirectionType(MovementDirection direction) + { + return direction switch + { + MovementDirection.Left => DirectionType.Left, + MovementDirection.Right => DirectionType.Right, + MovementDirection.Up => DirectionType.Up, + MovementDirection.Down => DirectionType.Down, + _ => DirectionType.Unknow, + }; + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MovementDirection.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..b8333ef --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/MovementDirection.cs @@ -0,0 +1,25 @@ + +namespace ProjectDumpTruck.MovementStrategy; + +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/ObjectParameters.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..6e0aba8 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,73 @@ + +namespace ProjectDumpTruck.MovementStrategy; + +/// +/// Параметры-координаты объекта +/// +public class ObjectParameters +{ + /// + /// Координата X + /// + private readonly int _x; + + /// + /// Координата Y + /// + private readonly int _y; + + /// + /// Ширина объекта + /// + private readonly int _width; + + /// + /// Высота объекта + /// + private readonly int _height; + + /// + /// Левая граница + /// + public int LeftBorder => _x; + + /// + /// Верхняя граница + /// + public int TopBorder => _y; + + /// + /// Правая граница + /// + public int RightBorder => _x + _width; + + /// + /// Нижняя граница + /// + public int DownBorder => _y + _height; + + /// + /// Середина объекта + /// + public int ObjectMiddleHorizontal => _x + _width / 2; + + /// + /// Середина объекта + /// + public int ObjectMiddleVertical => _y + _height / 2; + + /// + /// Конструктор + /// + /// Координата X + /// Координата Y + /// Ширина объекта + /// Высота объекта + public ObjectParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } +} diff --git a/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/StrategyStatus.cs b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..12d4487 --- /dev/null +++ b/ProjectDumpTruck/ProjectDumpTruck/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,23 @@ + +namespace ProjectDumpTruck.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +} \ No newline at end of file diff --git a/ProjectDumpTruck/ProjectDumpTruck/Program.cs b/ProjectDumpTruck/ProjectDumpTruck/Program.cs index 9539384..2711713 100644 --- a/ProjectDumpTruck/ProjectDumpTruck/Program.cs +++ b/ProjectDumpTruck/ProjectDumpTruck/Program.cs @@ -1,3 +1,5 @@ +using ProjectDumpTruck.MovementStrategy; + namespace ProjectDumpTruck { internal static class Program @@ -12,7 +14,15 @@ namespace ProjectDumpTruck // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); Application.Run(new FormTransport()); - + + + //// 3 + //AbstractStrategy myObject1 = new MoveToBorder(); + //myObject1.MyAbstractMethod(); + + //AbstractStrategy myObject2 = new MoveToCenter(); + //myObject2.MyAbstractMethod(); + } } } \ No newline at end of file