From 5eaaca59716487ed9c7db561f20d433c6190b940 Mon Sep 17 00:00:00 2001 From: bekodeg Date: Tue, 10 Oct 2023 19:30:57 +0400 Subject: [PATCH 1/2] =?UTF-8?q?=D1=81=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=B1=D0=B0=D0=B7=D0=BE=D0=B2=D1=8B=D1=85=20=D0=B8=20?= =?UTF-8?q?=D0=B4=D0=BE=D1=87=D0=B5=D1=80=D0=BD=D0=B8=D1=85=20=D0=BA=D0=BB?= =?UTF-8?q?=D0=B0=D1=81=D1=81=D0=BE=D0=B2=20=D0=B4=D0=BB=D1=8F=20=D1=85?= =?UTF-8?q?=D1=80=D0=B0=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BE=D1=82=D1=80?= =?UTF-8?q?=D0=B8=D1=81=D0=BE=D0=B2=D0=BA=D0=B8=20=D0=B8=20=D0=BB=D0=BE?= =?UTF-8?q?=D0=B3=D0=B8=D0=BA=D0=B8=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5?= =?UTF-8?q?=D1=89=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BE=D0=B1=D1=8A=D0=B5=D0=BA?= =?UTF-8?q?=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ElectricLocomotive.sln | 2 +- ElectricLocomotive/Direction.cs | 41 ++-- .../DrawningElectricLocomotive.cs | 68 ++++++ .../DrawningLocomotive.cs} | 196 ++++++++++-------- .../EntityElectricLocomotive.cs | 38 ++-- .../Entities/EntityLocomotive.cs | 46 ++++ .../FormElectricLocomotive.Designer.cs | 2 +- ElectricLocomotive/FormElectricLocomotive.cs | 2 +- .../LogicFormElectricLocomotive.cs | 6 +- .../MovementStrategy/AbstractStrategy.cs | 135 ++++++++++++ .../DrawningObjectLocomotive.cs | 42 ++++ .../MovementStrategy/IMoveableObject.cs | 37 ++++ .../MovementStrategy/MoveToCenter.cs | 60 ++++++ .../MovementStrategy/ObjectParameters.cs | 57 +++++ ElectricLocomotive/MovementStrategy/Status.cs | 18 ++ ElectricLocomotive/Program.cs | 2 +- ...sproj => ProjectElectricLocomotive.csproj} | 0 .../Properties/Resources.Designer.cs | 4 +- 18 files changed, 616 insertions(+), 140 deletions(-) create mode 100644 ElectricLocomotive/DrawningObjects/DrawningElectricLocomotive.cs rename ElectricLocomotive/{DrawningElectricLocomotive.cs => DrawningObjects/DrawningLocomotive.cs} (57%) rename ElectricLocomotive/{ => Entities}/EntityElectricLocomotive.cs (59%) create mode 100644 ElectricLocomotive/Entities/EntityLocomotive.cs create mode 100644 ElectricLocomotive/MovementStrategy/AbstractStrategy.cs create mode 100644 ElectricLocomotive/MovementStrategy/DrawningObjectLocomotive.cs create mode 100644 ElectricLocomotive/MovementStrategy/IMoveableObject.cs create mode 100644 ElectricLocomotive/MovementStrategy/MoveToCenter.cs create mode 100644 ElectricLocomotive/MovementStrategy/ObjectParameters.cs create mode 100644 ElectricLocomotive/MovementStrategy/Status.cs rename ElectricLocomotive/{ElectricLocomotive.csproj => ProjectElectricLocomotive.csproj} (100%) diff --git a/ElectricLocomotive.sln b/ElectricLocomotive.sln index d495089..3c6a955 100644 --- a/ElectricLocomotive.sln +++ b/ElectricLocomotive.sln @@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.7.34031.279 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElectricLocomotive", "ElectricLocomotive\ElectricLocomotive.csproj", "{F2E231D6-98A4-412A-952D-87456DBD3E48}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectElectricLocomotive", "ElectricLocomotive\ProjectElectricLocomotive.csproj", "{F2E231D6-98A4-412A-952D-87456DBD3E48}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/ElectricLocomotive/Direction.cs b/ElectricLocomotive/Direction.cs index bd07fd2..a41bbff 100644 --- a/ElectricLocomotive/Direction.cs +++ b/ElectricLocomotive/Direction.cs @@ -4,28 +4,27 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ElectricLocomotive +namespace ProjectElectricLocomotive; + +/// +/// Направление перемещения +/// +public enum DirectionType { /// - /// Направление перемещения + /// Вверх + /// /// + Up = 1, + /// + /// Вниз /// - public enum DirectionType - { - /// - /// Вверх - /// /// - Up = 1, - /// - /// Вниз - /// - Down = 2, - /// - /// Влево - /// - Left = 3, - /// - /// Вправо - /// - Right = 4 - } + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 } diff --git a/ElectricLocomotive/DrawningObjects/DrawningElectricLocomotive.cs b/ElectricLocomotive/DrawningObjects/DrawningElectricLocomotive.cs new file mode 100644 index 0000000..af4cfc0 --- /dev/null +++ b/ElectricLocomotive/DrawningObjects/DrawningElectricLocomotive.cs @@ -0,0 +1,68 @@ +using ProjectElectricLocomotive.Entities; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Net.NetworkInformation; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.DrawningObjects +{ + /// + /// Класс, отвечающий за прорисовку и перемещение объекта-сущности + /// + public class DrawningElectricLocomotive : DrawningLocomotive + { + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Дополнительный цвет + /// Признак наличия рогов + /// Признак наличия отсека для батарей + /// Ширина картинки + /// Высота картинки + public DrawningElectricLocomotive(int speed, double weight, Color bodyColor, + Color additionalColor, bool horns, bool battery, int width, int height) : + base(speed, weight, bodyColor, width, height, 120, 70) + { + if (EntityLocomotive != null) + { + EntityLocomotive = new EntityElectricLocomotive(speed, weight, bodyColor, additionalColor, horns, battery); + } + } + public override void DrawTransport(Graphics g) + { + if (EntityLocomotive is not EntityElectricLocomotive electricLocomotive) + { + return; + } + base.DrawTransport(g); + Pen pen = new(Color.Black, 5); + Brush brush = new SolidBrush(EntityLocomotive.BodyColor); + Point[] points; + // рога + if (electricLocomotive.Horns) + { + pen = new(Color.Black, 2); + points = new Point[4]; + points[0] = new Point(_startPosX + 50, _startPosY + 20); + points[1] = new Point(_startPosX + 40, _startPosY + 10); + points[2] = new Point(_startPosX + 50, _startPosY); + points[3] = new Point(_startPosX + 60, _startPosY + 10); + g.DrawPolygon(pen, points); + } + // отсек для батарей + if (electricLocomotive.Battery) + { + brush = new SolidBrush(electricLocomotive.AdditionalColor); + g.FillRectangle(brush, _startPosX + 80, _startPosY + 45, 35, 9); + } + } + } +} diff --git a/ElectricLocomotive/DrawningElectricLocomotive.cs b/ElectricLocomotive/DrawningObjects/DrawningLocomotive.cs similarity index 57% rename from ElectricLocomotive/DrawningElectricLocomotive.cs rename to ElectricLocomotive/DrawningObjects/DrawningLocomotive.cs index e9aa164..99007b6 100644 --- a/ElectricLocomotive/DrawningElectricLocomotive.cs +++ b/ElectricLocomotive/DrawningObjects/DrawningLocomotive.cs @@ -3,66 +3,97 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ProjectElectricLocomotive.Entities; +using ProjectElectricLocomotive; -namespace ElectricLocomotive +namespace ProjectElectricLocomotive.DrawningObjects { - internal class DrawningElectricLocomotive + /// + /// Класс, отвечающий за прорисовку и перемещение объекта-сущности + /// + public class DrawningLocomotive { /// /// Класс-сущность /// - public EntityElectricLocomotive? EntityElectricLocomotive { get; private set; } + public EntityLocomotive? EntityLocomotive { get; protected set; } /// /// Ширина окна /// - private int _pictureWidth; + protected int _pictureWidth; /// /// Высота окна /// - private int _pictureHeight; + protected int _pictureHeight; /// /// Левая координата прорисовки автомобиля /// - private int _startPosX; + protected int _startPosX; /// /// Верхняя кооридната прорисовки автомобиля /// - private int _startPosY; + protected int _startPosY; /// /// Ширина прорисовки автомобиля /// - private readonly int _locomotiveWidth = 120; + protected readonly int _locomotiveWidth = 120; /// /// Высота прорисовки автомобиля /// - private readonly int _locomotiveHeight = 70; + protected readonly int _locomotiveHeight = 70; + /// - /// Инициализация свойств + /// Координата X объекта + /// + public int GetPosX => _startPosX; + /// + /// Координата Y объекта + /// + public int GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _locomotiveWidth; + /// + /// Высота объекта + /// + public int GetHeight => _locomotiveHeight; + + /// + /// Конструктор /// /// Скорость /// Вес - /// Цвет кузова - /// Дополнительный цвет - /// Признак наличия рогов - /// Признак наличия отсека для батарей + /// Основной цвет /// Ширина картинки /// Высота картинки /// true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах - public bool Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool horns, bool battery, int width, int height) + public DrawningLocomotive(int speed, double weight, Color bodyColor, int width, int height) { if (width < _locomotiveWidth || height < _locomotiveHeight) { - return false; + return; } _pictureWidth = width; _pictureHeight = height; - EntityElectricLocomotive = new EntityElectricLocomotive(); - EntityElectricLocomotive.Init(speed, weight, bodyColor, additionalColor, - horns, battery); - return true; + EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor); } + + public DrawningLocomotive(int speed, double weight, Color bodyColor, + int width, int height, int locomotiveWidth, int locomotiveHeight) + { + if (width < _locomotiveWidth || height < _locomotiveHeight) + { + return; + } + _pictureWidth = width; + _pictureHeight = height; + _locomotiveWidth = locomotiveWidth; + _locomotiveHeight = locomotiveHeight; + EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor); + } + /// /// Установка позиции /// @@ -75,62 +106,21 @@ namespace ElectricLocomotive _startPosX = x; _startPosY = y; } - /// - /// Изменение направления перемещения - /// - /// Направление - public void MoveTransport(DirectionType direction) - { - if (EntityElectricLocomotive == null) - { - return; - } - switch (direction) - { - //влево - case DirectionType.Left: - if (_startPosX - EntityElectricLocomotive.Step > 0) - { - _startPosX -= (int)EntityElectricLocomotive.Step; - } - break; - //вверх - case DirectionType.Up: - if (_startPosY - EntityElectricLocomotive.Step > 0) - { - _startPosY -= (int)EntityElectricLocomotive.Step; - } - break; - // вправо - case DirectionType.Right: - if (_startPosX + _locomotiveWidth + EntityElectricLocomotive.Step < _pictureWidth) - { - _startPosX += (int)EntityElectricLocomotive.Step; - } - break; - //вниз - case DirectionType.Down: - if (_startPosY + _locomotiveHeight + EntityElectricLocomotive.Step < _pictureHeight) - { - _startPosY += (int)EntityElectricLocomotive.Step; - } - break; - } - } + /// /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { - if (EntityElectricLocomotive == null) + if (EntityLocomotive == null) { return; } // корпус электровоза Pen pen = new(Color.Black, 5); - Brush brush = new SolidBrush(EntityElectricLocomotive.BodyColor); + Brush brush = new SolidBrush(EntityLocomotive.BodyColor); Point[] points = new Point[5]; points[0] = new Point(_startPosX, _startPosY + 40); points[1] = new Point(_startPosX + 10, _startPosY + 20); @@ -156,24 +146,6 @@ namespace ElectricLocomotive g.FillEllipse(brush, _startPosX + 25, _startPosY + 55, 15, 15); g.FillEllipse(brush, _startPosX + 80, _startPosY + 55, 15, 15); g.FillEllipse(brush, _startPosX + 95, _startPosY + 55, 15, 15); - - // рога - if (EntityElectricLocomotive.Horns) - { - pen = new(Color.Black, 2); - points = new Point[4]; - points[0] = new Point(_startPosX + 50, _startPosY + 20); - points[1] = new Point(_startPosX + 40, _startPosY + 10); - points[2] = new Point(_startPosX + 50, _startPosY); - points[3] = new Point(_startPosX + 60, _startPosY + 10); - g.DrawPolygon(pen, points); - } - // отсек для батарей - if (EntityElectricLocomotive.Battery) - { - brush = new SolidBrush(EntityElectricLocomotive.AdditionalColor); - g.FillRectangle(brush, _startPosX + 80, _startPosY + 45, 35, 9); - } } /// @@ -186,5 +158,61 @@ namespace ElectricLocomotive _pictureWidth = newSize.Width; } + + /// + /// Проверка, что объект может переместится по указанному направлению + /// + /// Направление + /// true - можно переместится по указанному направлению + public bool CanMove(DirectionType direction) + { + if (EntityLocomotive == null) + { + return false; + } + return direction switch + { + //влево + DirectionType.Left => _startPosX - EntityLocomotive.Step > 0, + //вверх + DirectionType.Up => _startPosY - EntityLocomotive.Step > 0, + // вправо + DirectionType.Right => _startPosX + _locomotiveWidth + EntityLocomotive.Step < _pictureWidth, + //вниз + DirectionType.Down => _startPosY + _locomotiveHeight + EntityLocomotive.Step < _pictureHeight, + _ => false, + }; + } + /// + /// Изменение направления перемещения + /// + /// Направление + public void MoveTransport(DirectionType direction) + { + if (!CanMove(direction) || EntityLocomotive == null) + { + return; + } + switch (direction) + { + //влево + case DirectionType.Left: + _startPosX -= (int)EntityLocomotive.Step; + break; + //вверх + case DirectionType.Up: + _startPosY -= (int)EntityLocomotive.Step; + break; + // вправо + case DirectionType.Right: + _startPosX += (int)EntityLocomotive.Step; + break; + //вниз + case DirectionType.Down: + _startPosY += (int)EntityLocomotive.Step; + break; + } + } + } } diff --git a/ElectricLocomotive/EntityElectricLocomotive.cs b/ElectricLocomotive/Entities/EntityElectricLocomotive.cs similarity index 59% rename from ElectricLocomotive/EntityElectricLocomotive.cs rename to ElectricLocomotive/Entities/EntityElectricLocomotive.cs index 4d033c4..fb7cb99 100644 --- a/ElectricLocomotive/EntityElectricLocomotive.cs +++ b/ElectricLocomotive/Entities/EntityElectricLocomotive.cs @@ -1,26 +1,17 @@ using System; using System.Collections.Generic; -using System.Drawing; using System.Linq; +using System.Net.NetworkInformation; using System.Text; using System.Threading.Tasks; -namespace ElectricLocomotive +namespace ProjectElectricLocomotive.Entities { - internal class EntityElectricLocomotive + /// + /// Класс-сущность "Электровоз" + /// + public class EntityElectricLocomotive : EntityLocomotive { - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } /// /// Дополнительный цвет (для опциональных элементов) /// @@ -33,28 +24,23 @@ namespace ElectricLocomotive /// Признак (опция) наличия отсека для батарей /// public bool Battery { get; private set; } - /// - /// Шаг перемещения автомобиля - /// - public double Step => (double)Speed * 100 / Weight; + /// /// Инициализация полей объекта-класса спортивного автомобиля /// /// Скорость - /// Вес автомобиля - /// Основной цвет + /// Веc поезда + /// Основной цвет /// Дополнительный цвет /// Признак наличия рогов /// Признак наличия отсека для батарей - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool horns, bool battery) + public EntityElectricLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool battery) : + base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; AdditionalColor = additionalColor; Horns = horns; Battery = battery; } + } } diff --git a/ElectricLocomotive/Entities/EntityLocomotive.cs b/ElectricLocomotive/Entities/EntityLocomotive.cs new file mode 100644 index 0000000..f115bac --- /dev/null +++ b/ElectricLocomotive/Entities/EntityLocomotive.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Entities +{ + /// + /// Класс-сущность "Поезд" + /// + public class EntityLocomotive + { + /// + /// Скорость + /// + public int Speed { get; private set; } + /// + /// Вес + /// + public double Weight { get; private set; } + /// + /// Основной цвет + /// + public Color BodyColor { get; private set; } + + /// + /// Шаг перемещения автомобиля + /// + public double Step => (double)Speed * 100 / Weight; + /// + /// Конструктор с параметрами + /// + /// Скорость + /// Вес поезда + /// Основной цвет + + public EntityLocomotive(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } + } +} diff --git a/ElectricLocomotive/FormElectricLocomotive.Designer.cs b/ElectricLocomotive/FormElectricLocomotive.Designer.cs index 2052a79..93aca37 100644 --- a/ElectricLocomotive/FormElectricLocomotive.Designer.cs +++ b/ElectricLocomotive/FormElectricLocomotive.Designer.cs @@ -1,4 +1,4 @@ -namespace ElectricLocomotive +namespace ProjectElectricLocomotive { partial class FormElectricLocomotive { diff --git a/ElectricLocomotive/FormElectricLocomotive.cs b/ElectricLocomotive/FormElectricLocomotive.cs index d4e5df3..30d0a75 100644 --- a/ElectricLocomotive/FormElectricLocomotive.cs +++ b/ElectricLocomotive/FormElectricLocomotive.cs @@ -1,4 +1,4 @@ -namespace ElectricLocomotive +namespace ProjectElectricLocomotive { public partial class FormElectricLocomotive : Form { diff --git a/ElectricLocomotive/LogicFormElectricLocomotive.cs b/ElectricLocomotive/LogicFormElectricLocomotive.cs index 72f1867..2c2d557 100644 --- a/ElectricLocomotive/LogicFormElectricLocomotive.cs +++ b/ElectricLocomotive/LogicFormElectricLocomotive.cs @@ -1,11 +1,11 @@ -using ElectricLocomotive; +using ProjectElectricLocomotive.DrawningObjects; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ElectricLocomotive +namespace ProjectElectricLocomotive { /// /// Форма работы с объектом "электровоз" @@ -15,7 +15,7 @@ namespace ElectricLocomotive /// /// Поле-объект для прорисовки объекта /// - private DrawningElectricLocomotive? _drawningElectricLocomotive; + private DrawningLocomotive? _drawningElectricLocomotive; /// /// Инициализация формы /// diff --git a/ElectricLocomotive/MovementStrategy/AbstractStrategy.cs b/ElectricLocomotive/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..b3d46e6 --- /dev/null +++ b/ElectricLocomotive/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,135 @@ +using ElectricLocomotive; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using static System.Windows.Forms.AxHost; + +namespace ProjectElectricLocomotive.MovementStrategy +{ + /// + /// Класс-стратегия перемещения объекта + /// + public abstract class AbstractStrategy + { + /// + /// Перемещаемый объект + /// + private IMoveableObject? _moveableObject; + /// + /// Статус перемещения + /// + private Status _state = Status.NotInit; + /// + /// Ширина поля + /// + protected int FieldWidth { get; private set; } + /// + /// Высота поля + /// + protected int FieldHeight { get; private set; } + /// + /// Статус перемещения + /// + public Status GetStatus() { return _state; } + /// + /// Установка данных + /// + /// Перемещаемый объект + /// Ширина поля + /// Высота поля + public void SetData(IMoveableObject moveableObject, int width, int height) + { + if (moveableObject == null) + { + _state = Status.NotInit; + return; + } + _state = Status.InProgress; + _moveableObject = moveableObject; + FieldWidth = width; + FieldHeight = height; + } + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != Status.InProgress) + { + return; + } + if (IsTargetDestinaion()) + { + _state = Status.Finish; + return; + } + MoveToTarget(); + } + /// + /// Перемещение влево + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveLeft() => MoveTo(DirectionType.Left); + /// + /// Перемещение вправо + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveRight() => MoveTo(DirectionType.Right); + /// + /// Перемещение вверх + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveUp() => MoveTo(DirectionType.Up); + /// + /// Перемещение вниз + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveDown() => MoveTo(DirectionType.Down); + /// + /// Параметры объекта + /// + protected ObjectParameters? GetObjectParameters => + _moveableObject?.GetObjectPosition; + /// + /// Шаг объекта + /// + /// + protected int? GetStep() + { + if (_state != Status.InProgress) + { + return null; + } + return _moveableObject?.GetStep; + } + /// + /// Перемещение к цели + /// + protected abstract void MoveToTarget(); + /// + /// Достигнута ли цель + /// + /// + protected abstract bool IsTargetDestinaion(); + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат попытки (true - удалось переместиться, false - неудача) + private bool MoveTo(DirectionType directionType) + { + if (_state != Status.InProgress) + { + return false; + } + if (_moveableObject?.CheckCanMove(directionType) ?? false) + { + _moveableObject.MoveObject(directionType); + return true; + } + return false; + } + } +} diff --git a/ElectricLocomotive/MovementStrategy/DrawningObjectLocomotive.cs b/ElectricLocomotive/MovementStrategy/DrawningObjectLocomotive.cs new file mode 100644 index 0000000..a2ca5d1 --- /dev/null +++ b/ElectricLocomotive/MovementStrategy/DrawningObjectLocomotive.cs @@ -0,0 +1,42 @@ +using ProjectElectricLocomotive.DrawningObjects; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy +{ + /// + /// Реализация интерфейса IDrawningObject для работы с объектом DrawningLocomotive(паттерн Adapter) + /// + public class DrawningObjectLocomotive : IMoveableObject + { + private readonly DrawningLocomotive? _drawningLocomotive = null; + + public DrawningObjectLocomotive(DrawningLocomotive drawningLocomotive) + { + _drawningLocomotive = drawningLocomotive; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_drawningLocomotive == null || _drawningLocomotive.EntityLocomotive == + null) + { + return null; + } + return new ObjectParameters(_drawningLocomotive.GetPosX, + _drawningLocomotive.GetPosY, _drawningLocomotive.GetWidth, _drawningLocomotive.GetHeight); + } + } + + public int GetStep => (int)(_drawningLocomotive?.EntityLocomotive?.Step ?? 0); + + public bool CheckCanMove(DirectionType direction) => _drawningLocomotive?.CanMove(direction) ?? false; + + public void MoveObject(DirectionType direction) => _drawningLocomotive?.MoveTransport(direction); + } +} diff --git a/ElectricLocomotive/MovementStrategy/IMoveableObject.cs b/ElectricLocomotive/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..2411487 --- /dev/null +++ b/ElectricLocomotive/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using ProjectElectricLocomotive; + +namespace ProjectElectricLocomotive.MovementStrategy +{ + /// + /// Интерфейс для работы с перемещаемым объектом + /// + public interface IMoveableObject + { + /// + /// Получение координаты X объекта + /// + ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Проверка, можно ли переместиться по нужному направлению + /// + /// + /// + bool CheckCanMove(DirectionType direction); + /// + /// Изменение направления пермещения объекта + /// + /// Направление + void MoveObject(DirectionType direction); + } + +} diff --git a/ElectricLocomotive/MovementStrategy/MoveToCenter.cs b/ElectricLocomotive/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..2d766c2 --- /dev/null +++ b/ElectricLocomotive/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy +{ + /// + /// Стратегия перемещения объекта в центр экрана + /// + public class MoveToCenter : AbstractStrategy + { + protected override bool IsTargetDestinaion() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 && + objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 && + objParams.ObjectMiddleVertical <= FieldHeight / 2 && + objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2; + } + protected override void MoveToTarget() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } + } + +} diff --git a/ElectricLocomotive/MovementStrategy/ObjectParameters.cs b/ElectricLocomotive/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..37b97c8 --- /dev/null +++ b/ElectricLocomotive/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy +{ + /// + /// Параметры-координаты объекта + /// + public class ObjectParameters + { + private readonly int _x; + 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/ElectricLocomotive/MovementStrategy/Status.cs b/ElectricLocomotive/MovementStrategy/Status.cs new file mode 100644 index 0000000..d7b2b48 --- /dev/null +++ b/ElectricLocomotive/MovementStrategy/Status.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy +{ + /// + /// Статус выполнения операции перемещения + /// + public enum Status + { + NotInit, + InProgress, + Finish + } +} diff --git a/ElectricLocomotive/Program.cs b/ElectricLocomotive/Program.cs index 3c929fb..ddb490c 100644 --- a/ElectricLocomotive/Program.cs +++ b/ElectricLocomotive/Program.cs @@ -1,4 +1,4 @@ -namespace ElectricLocomotive +namespace ProjectElectricLocomotive { internal static class Program { diff --git a/ElectricLocomotive/ElectricLocomotive.csproj b/ElectricLocomotive/ProjectElectricLocomotive.csproj similarity index 100% rename from ElectricLocomotive/ElectricLocomotive.csproj rename to ElectricLocomotive/ProjectElectricLocomotive.csproj diff --git a/ElectricLocomotive/Properties/Resources.Designer.cs b/ElectricLocomotive/Properties/Resources.Designer.cs index f455d2d..04f8cca 100644 --- a/ElectricLocomotive/Properties/Resources.Designer.cs +++ b/ElectricLocomotive/Properties/Resources.Designer.cs @@ -8,7 +8,7 @@ // //------------------------------------------------------------------------------ -namespace ElectricLocomotive.Properties { +namespace ProjectElectricLocomotive.Properties { using System; @@ -39,7 +39,7 @@ namespace ElectricLocomotive.Properties { internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ElectricLocomotive.Properties.Resources", typeof(Resources).Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectElectricLocomotive.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; -- 2.25.1 From d25d9a4ea5ffa61ef4a0650013a6d240ea31e3b8 Mon Sep 17 00:00:00 2001 From: bekodeg Date: Fri, 13 Oct 2023 10:40:45 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D1=81=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D1=81=D1=82=D1=80=D0=B0=D1=82=D0=B5=D0=B3=D0=B8=D0=B8?= =?UTF-8?q?=20=D0=B4=D0=BE=D1=85=D0=BE=D0=B6=D0=B4=D0=B5=D0=BD=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=B4=D0=BE=20=D0=B3=D1=80=D0=B0=D0=BD=D0=B8=D1=86=D1=8B,?= =?UTF-8?q?=20=D0=BE=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5?= =?UTF-8?q?=20=D1=84=D0=BE=D1=80=D0=BC=D1=8B=20=D0=B8=20=D0=BF=D0=BE=D0=B4?= =?UTF-8?q?=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D0=BE=D0=B3=D0=BE=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8?= =?UTF-8?q?=D0=BE=D0=BD=D0=B0=D0=BB=D0=B0=20=D0=BA=20=D1=8D=D0=BB=D0=B5?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D0=BC=20=D1=83=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FormElectricLocomotive.Designer.cs | 86 +++++++++--- ElectricLocomotive/FormElectricLocomotive.cs | 16 ++- .../LogicFormElectricLocomotive.cs | 129 ++++++++++++++---- .../MovementStrategy/AbstractStrategy.cs | 12 +- .../MovementStrategy/MoveToBorder.cs | 45 ++++++ ElectricLocomotive/Program.cs | 2 +- 6 files changed, 233 insertions(+), 57 deletions(-) create mode 100644 ElectricLocomotive/MovementStrategy/MoveToBorder.cs diff --git a/ElectricLocomotive/FormElectricLocomotive.Designer.cs b/ElectricLocomotive/FormElectricLocomotive.Designer.cs index 93aca37..ab9f09c 100644 --- a/ElectricLocomotive/FormElectricLocomotive.Designer.cs +++ b/ElectricLocomotive/FormElectricLocomotive.Designer.cs @@ -1,6 +1,6 @@ namespace ProjectElectricLocomotive { - partial class FormElectricLocomotive + partial class FormLocomotive { /// /// Required designer variable. @@ -30,10 +30,13 @@ { buttonUp = new Button(); buttonRight = new Button(); - buttonCreate = new Button(); + buttonCreateLocomotive = new Button(); buttonDown = new Button(); buttonLeft = new Button(); pictureBoxElectricLocomotive = new PictureBox(); + buttonCreateElectricLocomotive = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).BeginInit(); SuspendLayout(); // @@ -42,7 +45,7 @@ buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonUp.BackgroundImage = Properties.Resources.arrowUp; buttonUp.BackgroundImageLayout = ImageLayout.Zoom; - buttonUp.Location = new Point(55, 459); + buttonUp.Location = new Point(54, 514); buttonUp.Margin = new Padding(3, 4, 3, 4); buttonUp.Name = "buttonUp"; buttonUp.Size = new Size(34, 40); @@ -56,7 +59,7 @@ buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonRight.BackgroundImage = Properties.Resources.arrowRight; buttonRight.BackgroundImageLayout = ImageLayout.Zoom; - buttonRight.Location = new Point(96, 507); + buttonRight.Location = new Point(95, 562); buttonRight.Margin = new Padding(3, 4, 3, 4); buttonRight.Name = "buttonRight"; buttonRight.Size = new Size(34, 40); @@ -65,24 +68,24 @@ buttonRight.UseVisualStyleBackColor = true; buttonRight.Click += buttonRight_Click; // - // buttonCreate + // buttonCreateLocomotive // - buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(14, 559); - buttonCreate.Margin = new Padding(3, 4, 3, 4); - buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(117, 40); - buttonCreate.TabIndex = 2; - buttonCreate.Text = "создать"; - buttonCreate.UseVisualStyleBackColor = true; - buttonCreate.Click += buttonCreate_Click; + buttonCreateLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonCreateLocomotive.Location = new Point(816, 562); + buttonCreateLocomotive.Margin = new Padding(3, 4, 3, 4); + buttonCreateLocomotive.Name = "buttonCreateLocomotive"; + buttonCreateLocomotive.Size = new Size(182, 40); + buttonCreateLocomotive.TabIndex = 2; + buttonCreateLocomotive.Text = "создать локомотив"; + buttonCreateLocomotive.UseVisualStyleBackColor = true; + buttonCreateLocomotive.Click += buttonCreateLocomotive_Click; // // buttonDown // buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonDown.BackgroundImage = Properties.Resources.arrowDown; buttonDown.BackgroundImageLayout = ImageLayout.Zoom; - buttonDown.Location = new Point(55, 507); + buttonDown.Location = new Point(54, 562); buttonDown.Margin = new Padding(3, 4, 3, 4); buttonDown.Name = "buttonDown"; buttonDown.Size = new Size(34, 40); @@ -96,7 +99,7 @@ buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonLeft.BackgroundImage = Properties.Resources.arrowLeft; buttonLeft.BackgroundImageLayout = ImageLayout.Zoom; - buttonLeft.Location = new Point(14, 507); + buttonLeft.Location = new Point(13, 562); buttonLeft.Margin = new Padding(3, 4, 3, 4); buttonLeft.Name = "buttonLeft"; buttonLeft.Size = new Size(34, 40); @@ -116,20 +119,58 @@ pictureBoxElectricLocomotive.TabStop = false; pictureBoxElectricLocomotive.SizeChanged += pictureBoxElectricLocomotive_SizeChanged; // - // FormElectricLocomotive + // buttonCreateElectricLocomotive + // + buttonCreateElectricLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonCreateElectricLocomotive.Location = new Point(816, 514); + buttonCreateElectricLocomotive.Margin = new Padding(3, 4, 3, 4); + buttonCreateElectricLocomotive.Name = "buttonCreateElectricLocomotive"; + buttonCreateElectricLocomotive.Size = new Size(182, 40); + buttonCreateElectricLocomotive.TabIndex = 6; + buttonCreateElectricLocomotive.Text = "создать электропоезд"; + buttonCreateElectricLocomotive.UseVisualStyleBackColor = true; + buttonCreateElectricLocomotive.Click += buttonCreateElectricLocomotive_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right; + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "идти к центру экрана", "идти к краю экрана" }); + comboBoxStrategy.Location = new Point(816, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(182, 28); + comboBoxStrategy.TabIndex = 7; + // + // buttonStep + // + buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonStep.Location = new Point(915, 47); + buttonStep.Margin = new Padding(3, 4, 3, 4); + buttonStep.Name = "buttonStep"; + buttonStep.Size = new Size(83, 33); + buttonStep.TabIndex = 8; + buttonStep.Text = "шаг"; + buttonStep.UseVisualStyleBackColor = true; + buttonStep.Click += buttonStep_Click; + // + // FormLocomotive // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(1010, 615); + Controls.Add(buttonStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreateElectricLocomotive); Controls.Add(buttonLeft); Controls.Add(buttonDown); - Controls.Add(buttonCreate); + Controls.Add(buttonCreateLocomotive); Controls.Add(buttonRight); Controls.Add(buttonUp); Controls.Add(pictureBoxElectricLocomotive); Margin = new Padding(3, 4, 3, 4); - MinimumSize = new Size(100, 100); - Name = "FormElectricLocomotive"; + MinimumSize = new Size(500, 300); + Name = "FormLocomotive"; Text = "ElectricLocomotive"; ((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).EndInit(); ResumeLayout(false); @@ -140,9 +181,12 @@ private Button buttonUp; private Button buttonRight; - private Button buttonCreate; + private Button buttonCreateLocomotive; private Button buttonDown; private Button buttonLeft; private PictureBox pictureBoxElectricLocomotive; + private Button buttonCreateElectricLocomotive; + private ComboBox comboBoxStrategy; + private Button buttonStep; } } \ No newline at end of file diff --git a/ElectricLocomotive/FormElectricLocomotive.cs b/ElectricLocomotive/FormElectricLocomotive.cs index 30d0a75..16c282b 100644 --- a/ElectricLocomotive/FormElectricLocomotive.cs +++ b/ElectricLocomotive/FormElectricLocomotive.cs @@ -1,10 +1,10 @@ namespace ProjectElectricLocomotive { - public partial class FormElectricLocomotive : Form + public partial class FormLocomotive : Form { - private void buttonCreate_Click(object sender, EventArgs e) + private void buttonCreateLocomotive_Click(object sender, EventArgs e) { - ButtonCreateElectricLocomotive_Click(sender, e); + ButtonCreateLocomotive_Click(sender, e); } private void buttonUp_Click(object sender, EventArgs e) @@ -31,5 +31,15 @@ namespace ProjectElectricLocomotive { PictureBoxElectricLocomotive_SizeChanged(sender, e); } + + private void buttonStep_Click(object sender, EventArgs e) + { + ButtonStep_Click(sender, e); + } + + private void buttonCreateElectricLocomotive_Click(object sender, EventArgs e) + { + ButtonCreateElectricLocomotive_Click(sender, e); + } } } \ No newline at end of file diff --git a/ElectricLocomotive/LogicFormElectricLocomotive.cs b/ElectricLocomotive/LogicFormElectricLocomotive.cs index 2c2d557..4838d11 100644 --- a/ElectricLocomotive/LogicFormElectricLocomotive.cs +++ b/ElectricLocomotive/LogicFormElectricLocomotive.cs @@ -1,4 +1,5 @@ using ProjectElectricLocomotive.DrawningObjects; +using ProjectElectricLocomotive.MovementStrategy; using System; using System.Collections.Generic; using System.Linq; @@ -10,16 +11,20 @@ namespace ProjectElectricLocomotive /// /// Форма работы с объектом "электровоз" /// - public partial class FormElectricLocomotive + public partial class FormLocomotive { /// /// Поле-объект для прорисовки объекта /// - private DrawningLocomotive? _drawningElectricLocomotive; + private DrawningLocomotive? _drawningLocomotive; + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _abstractStrategy; /// /// Инициализация формы /// - public FormElectricLocomotive() + public FormLocomotive() { InitializeComponent(); } @@ -28,46 +33,80 @@ namespace ProjectElectricLocomotive /// private void Draw() { - if (_drawningElectricLocomotive == null) + if (_drawningLocomotive == null) { return; } Bitmap bmp = new(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningElectricLocomotive.DrawTransport(gr); + _drawningLocomotive.DrawTransport(gr); pictureBoxElectricLocomotive.Image = bmp; } - - /// Обработка нажатия кнопки "Создать" + + /// Обработка нажатия кнопки "Создать электровоз" /// /// /// private void ButtonCreateElectricLocomotive_Click(object sender, EventArgs e) { Random random = new(); - _drawningElectricLocomotive = new DrawningElectricLocomotive(); - _drawningElectricLocomotive.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)), - pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); - _drawningElectricLocomotive.SetPosition(random.Next(10, 100), - random.Next(10, 100)); + _drawningLocomotive = new DrawningElectricLocomotive( + 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)), + pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); + _drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); Draw(); } + + /// + /// Обработка нажатия кнопки "Создать локомотив" + /// + /// + /// + private void ButtonCreateLocomotive_Click(object sender, EventArgs e) + { + Random random = new(); + _drawningLocomotive = new DrawningLocomotive( + random.Next(100, 300), + random.Next(1000, 3000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); + _drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); + Draw(); + } + /// /// Изменение размеров формы /// /// /// + private void PictureBoxElectricLocomotive_SizeChanged(object sender, EventArgs e) + { + Size size = ((PictureBox)sender)?.Size ?? Size.Empty; + + if (_abstractStrategy != null) + { + _abstractStrategy.SetFieldSize(size); + } + if (_drawningLocomotive != null) + { + _drawningLocomotive.SetPictureSize(size); + } + } + + /// + /// Изменение положения автомобиля + /// + /// + /// private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningElectricLocomotive == null) + if (_drawningLocomotive == null) { return; } @@ -75,29 +114,63 @@ namespace ProjectElectricLocomotive switch (name) { case "buttonUp": - _drawningElectricLocomotive.MoveTransport(DirectionType.Up); + _drawningLocomotive.MoveTransport(DirectionType.Up); break; case "buttonDown": - _drawningElectricLocomotive.MoveTransport(DirectionType.Down); + _drawningLocomotive.MoveTransport(DirectionType.Down); break; case "buttonLeft": - _drawningElectricLocomotive.MoveTransport(DirectionType.Left); + _drawningLocomotive.MoveTransport(DirectionType.Left); break; case "buttonRight": - _drawningElectricLocomotive.MoveTransport(DirectionType.Right); + _drawningLocomotive.MoveTransport(DirectionType.Right); break; } Draw(); } - private void PictureBoxElectricLocomotive_SizeChanged(object sender, EventArgs e) + /// + /// Обработка нажатия кнопки "Шаг" + /// + /// + /// + private void ButtonStep_Click(object sender, EventArgs e) { - if (_drawningElectricLocomotive == null) + if (_drawningLocomotive == null) { return; } - Size size = ((PictureBox)sender)?.Size ?? Size.Empty; - _drawningElectricLocomotive.SetPictureSize(size); + if (comboBoxStrategy.Enabled) + { + _abstractStrategy = comboBoxStrategy.SelectedIndex + switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_abstractStrategy == null) + { + return; + } + _abstractStrategy.SetData(new + DrawningObjectLocomotive(_drawningLocomotive), pictureBoxElectricLocomotive.Width, + pictureBoxElectricLocomotive.Height); + comboBoxStrategy.Enabled = false; + } + if (_abstractStrategy == null) + { + return; + } + _abstractStrategy.MakeStep(); + Draw(); + if (_abstractStrategy.GetStatus() == Status.Finish) + { + comboBoxStrategy.Enabled = true; + _abstractStrategy = null; + } } + + } } diff --git a/ElectricLocomotive/MovementStrategy/AbstractStrategy.cs b/ElectricLocomotive/MovementStrategy/AbstractStrategy.cs index b3d46e6..0b559f0 100644 --- a/ElectricLocomotive/MovementStrategy/AbstractStrategy.cs +++ b/ElectricLocomotive/MovementStrategy/AbstractStrategy.cs @@ -1,5 +1,4 @@ -using ElectricLocomotive; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -90,8 +89,7 @@ namespace ProjectElectricLocomotive.MovementStrategy /// /// Параметры объекта /// - protected ObjectParameters? GetObjectParameters => - _moveableObject?.GetObjectPosition; + protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition; /// /// Шаг объекта /// @@ -131,5 +129,11 @@ namespace ProjectElectricLocomotive.MovementStrategy } return false; } + + public void SetFieldSize(Size newSize) + { + FieldWidth = newSize.Width; + FieldHeight = newSize.Height; + } } } diff --git a/ElectricLocomotive/MovementStrategy/MoveToBorder.cs b/ElectricLocomotive/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..6357902 --- /dev/null +++ b/ElectricLocomotive/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy +{ + /// + /// Стратегия перемещения объекта к границе экрана экрана + /// + internal class MoveToBorder : AbstractStrategy + { + protected override bool IsTargetDestinaion() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + if (MoveRight()) + { + MoveLeft(); + return false; + } + if (MoveDown()) + { + MoveUp(); + return false; + } + return true; + } + protected override void MoveToTarget() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + + MoveRight(); + MoveDown(); + } + } +} diff --git a/ElectricLocomotive/Program.cs b/ElectricLocomotive/Program.cs index ddb490c..ca0ba7e 100644 --- a/ElectricLocomotive/Program.cs +++ b/ElectricLocomotive/Program.cs @@ -11,7 +11,7 @@ namespace ProjectElectricLocomotive // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormElectricLocomotive()); + Application.Run(new FormLocomotive()); } } } \ No newline at end of file -- 2.25.1