From 8dc70caf091503d84c10ef2d00e8b1dab6673fc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=B8=D0=BB=D1=8C=D1=8F?= Date: Fri, 26 Apr 2024 17:45:56 +0400 Subject: [PATCH] s --- .../ProjectLocomotive/DirectionType.cs | 23 ---- .../Drawnings/DirectionType.cs | 27 ++++ .../{ => Drawnings}/DrawningLocomotive.cs | 120 ++++++++-------- .../Drawnings/DrawningTLocomotive.cs | 72 ++++++++++ .../Entities/EntityLocomotiev.cs | 38 ++++++ .../Entities/EntityTLocomotive.cs | 30 ++++ .../ProjectLocomotive/EntityLocomotive.cs | 62 --------- .../FormLocomotive.Designer.cs | 79 ++++++++--- .../ProjectLocomotive/FormLocomotive.cs | 128 ++++++++++++++---- .../MovementStrategy/AbstractStrategy.cs | 123 +++++++++++++++++ .../MovementStrategy/IMoveableObject.cs | 24 ++++ .../MovementStrategy/MoveToBorder.cs | 53 ++++++++ .../MovementStrategy/MoveToCenter.cs | 53 ++++++++ .../MovementStrategy/MoveableTrain.cs | 62 +++++++++ .../MovementStrategy/MovementDirection.cs | 26 ++++ .../MovementStrategy/ObjectParameters.cs | 64 +++++++++ .../MovementStrategy/StrategyStatus.cs | 22 +++ 17 files changed, 819 insertions(+), 187 deletions(-) delete mode 100644 ProjectLocomotive/ProjectLocomotive/DirectionType.cs create mode 100644 ProjectLocomotive/ProjectLocomotive/Drawnings/DirectionType.cs rename ProjectLocomotive/ProjectLocomotive/{ => Drawnings}/DrawningLocomotive.cs (69%) create mode 100644 ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningTLocomotive.cs create mode 100644 ProjectLocomotive/ProjectLocomotive/Entities/EntityLocomotiev.cs create mode 100644 ProjectLocomotive/ProjectLocomotive/Entities/EntityTLocomotive.cs delete mode 100644 ProjectLocomotive/ProjectLocomotive/EntityLocomotive.cs create mode 100644 ProjectLocomotive/ProjectLocomotive/MovementStrategy/AbstractStrategy.cs create mode 100644 ProjectLocomotive/ProjectLocomotive/MovementStrategy/IMoveableObject.cs create mode 100644 ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveToBorder.cs create mode 100644 ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveToCenter.cs create mode 100644 ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveableTrain.cs create mode 100644 ProjectLocomotive/ProjectLocomotive/MovementStrategy/MovementDirection.cs create mode 100644 ProjectLocomotive/ProjectLocomotive/MovementStrategy/ObjectParameters.cs create mode 100644 ProjectLocomotive/ProjectLocomotive/MovementStrategy/StrategyStatus.cs diff --git a/ProjectLocomotive/ProjectLocomotive/DirectionType.cs b/ProjectLocomotive/ProjectLocomotive/DirectionType.cs deleted file mode 100644 index e26cd36..0000000 --- a/ProjectLocomotive/ProjectLocomotive/DirectionType.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace ProjectLocomotive; -/// -/// Направление перемещения -/// -public enum DirectionType -{ - /// - /// Вверх - /// - Up = 1, - /// - /// Вниз - /// - Down = 2, - /// - /// Влево - /// - Left = 3, - /// - /// Вправо - /// - Right = 4 -} diff --git a/ProjectLocomotive/ProjectLocomotive/Drawnings/DirectionType.cs b/ProjectLocomotive/ProjectLocomotive/Drawnings/DirectionType.cs new file mode 100644 index 0000000..cd8d4d5 --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/Drawnings/DirectionType.cs @@ -0,0 +1,27 @@ +namespace ProjectLocomotive.Drawnings; +/// +/// +/// +public enum DirectionType +{ + /// + /// + /// + Unknow = -1, + /// + /// + /// + Up = 1, + /// + /// + /// + Down = 2, + /// + /// + /// + Left = 3, + /// + /// + /// + Right = 4 +} diff --git a/ProjectLocomotive/ProjectLocomotive/DrawningLocomotive.cs b/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningLocomotive.cs similarity index 69% rename from ProjectLocomotive/ProjectLocomotive/DrawningLocomotive.cs rename to ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningLocomotive.cs index 8aae0e9..948988a 100644 --- a/ProjectLocomotive/ProjectLocomotive/DrawningLocomotive.cs +++ b/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningLocomotive.cs @@ -1,9 +1,7 @@ -using ProjectLocomotive; -using System.Drawing; +using ProjectLocomotive.Entities; using System.Drawing.Drawing2D; -using System.Security.Cryptography.Xml; -namespace ProjectLocomotive; +namespace ProjectLocomotive.Drawnings; /// /// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// @@ -12,7 +10,7 @@ public class DrawningLocomotive /// /// Класс-сущность /// - public EntityLocomotive? EntityLocomotive { get; private set; } + public EntityLocomotiev? EntityLocomotive { get; protected set; } /// /// Ширина окна /// @@ -24,11 +22,11 @@ public class DrawningLocomotive /// /// Левая координата прорисовки автомобиля /// - private int? _startPosX; + protected int? _startPosX; /// /// Верхняя кооридната прорисовки автомобиля /// - private int? _startPosY; + protected int? _startPosY; /// /// Ширина прорисовки поезда @@ -39,28 +37,56 @@ public class DrawningLocomotive /// private readonly int _drawningLocomotiveHeight = 50; private readonly int _drawningEnginesWidth = 3; - /// - /// Инициализация свойств - /// - /// Скорость - /// Вес - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия вертолетной площадки - /// Признак наличия шлюпок - /// Признак наличия пушки - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool pipe, bool fueltank, bool headlight) + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _drawningLocomotiveWidth; + /// + /// Высота объекта + /// + public int GetHeight => _drawningLocomotiveHeight; + + /// + /// Пустой онструктор + /// + private DrawningLocomotive() { - EntityLocomotive = new EntityLocomotive(); - EntityLocomotive.Init(speed, weight, bodyColor, additionalColor, - pipe, fueltank, headlight); _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + public DrawningLocomotive(int speed, double weight, Color bodyColor) : this() + { + EntityLocomotive = new EntityLocomotiev(speed, weight, bodyColor); + } + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки автомобиля + /// Высота прорисовки автомобиля + protected DrawningLocomotive(int drawningCarWidth, int drawningCarHeight) : this() + { + _drawningLocomotiveWidth = drawningCarWidth; + _pictureHeight = drawningCarHeight; + } + /// /// Установка границ поля /// @@ -162,7 +188,7 @@ public class DrawningLocomotive /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) @@ -172,28 +198,27 @@ public class DrawningLocomotive Pen pen = new(Color.Black, 2); Pen pen2 = new(Color.White, 1); - Pen pen3 = new(Color.Black, 3); Brush wheelBrush = new SolidBrush(Color.Black); Brush wheelBrush2 = new SolidBrush(Color.Gray); Brush headlightBrush = new SolidBrush(Color.Yellow); Brush glassBrush = new SolidBrush(Color.Cyan); - Brush FueltankBrush = new HatchBrush(HatchStyle.ZigZag, EntityLocomotive.AdditionalColor, Color.FromArgb(163, 163, 163)); - Brush additionalBrush = new SolidBrush(EntityLocomotive.AdditionalColor); + //Brush ElectroBrush = new HatchBrush(HatchStyle.ZigZag, entityTLocomotive.AdditionalColor, Color.FromArgb(163, 163, 163)); + //Brush additionalBrush = new SolidBrush(entityTLocomotive.AdditionalColor); Brush bodyBrush = new SolidBrush(EntityLocomotive.BodyColor); //границы круисера - Point[] points = { new Point(_startPosX.Value + 2, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value + 20), new Point(_startPosX.Value, _startPosY.Value + 20) }; - g.FillPolygon(additionalBrush, points); - g.DrawPolygon(pen, points); + Point[] points = { new Point(_startPosX.Value + 5, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value + 20), new Point(_startPosX.Value, _startPosY.Value + 20) }; + //g.FillPolygon(additionalBrush, points); + g.FillRectangle(bodyBrush, _startPosX.Value, _startPosY.Value + 20, 140, 20); g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 20, 140, 20); - - //g.DrawLine(pen, _startPosX.Value + 2, _startPosY.Value, _startPosX.Value + 140, _startPosY.Value); - //g.DrawLine(pen, _startPosX.Value + 140, _startPosY.Value, _startPosX.Value + 140, _startPosY.Value + 20); - - //g.DrawLine(pen, _startPosX.Value, _startPosY.Value + 20, _startPosX.Value + 5, _startPosY.Value ); + + g.DrawLine(pen, _startPosX.Value + 5, _startPosY.Value, _startPosX.Value + 140, _startPosY.Value); + g.DrawLine(pen, _startPosX.Value + 140, _startPosY.Value, _startPosX.Value + 140, _startPosY.Value + 20); + + g.DrawLine(pen, _startPosX.Value, _startPosY.Value + 20, _startPosX.Value + 5, _startPosY.Value); g.FillRectangle(wheelBrush, _startPosX.Value + 140, _startPosY.Value + 3, 7, 34); @@ -207,13 +232,12 @@ public class DrawningLocomotive g.FillRectangle(glassBrush, _startPosX.Value + 124, _startPosY.Value + 3, 13, 14); //колёса - Point[] points2 = { new Point(_startPosX.Value + 5 , _startPosY.Value + 40), new Point(_startPosX.Value + 55, _startPosY.Value + 40), new Point(_startPosX.Value + 45, _startPosY.Value + 47), new Point(_startPosX.Value - 5, _startPosY.Value + 47) }; + Point[] points2 = { new Point(_startPosX.Value + 5, _startPosY.Value + 40), new Point(_startPosX.Value + 55, _startPosY.Value + 40), new Point(_startPosX.Value + 45, _startPosY.Value + 47), new Point(_startPosX.Value - 5, _startPosY.Value + 47) }; g.FillPolygon(wheelBrush, points2); Point[] points3 = { new Point(_startPosX.Value + 145, _startPosY.Value + 47), new Point(_startPosX.Value + 95, _startPosY.Value + 47), new Point(_startPosX.Value + 85, _startPosY.Value + 40), new Point(_startPosX.Value + 135, _startPosY.Value + 40) }; g.FillPolygon(wheelBrush, points3); - g.FillEllipse(wheelBrush2, _startPosX.Value + 37, _startPosY.Value + 41, 14, 14); g.DrawEllipse(pen2, _startPosX.Value + 37, _startPosY.Value + 41, 15, 15); g.FillEllipse(wheelBrush2, _startPosX.Value + 10, _startPosY.Value + 41, 14, 14); @@ -223,28 +247,6 @@ public class DrawningLocomotive g.DrawEllipse(pen2, _startPosX.Value + 93, _startPosY.Value + 41, 15, 15); g.FillEllipse(wheelBrush2, _startPosX.Value + 120, _startPosY.Value + 41, 14, 14); g.DrawEllipse(pen2, _startPosX.Value + 120, _startPosY.Value + 41, 15, 15); - - - //внутренности поезда - if (EntityLocomotive.Pipe) - { - Point[] points4 = { new Point(_startPosX.Value + 20, _startPosY.Value ), new Point(_startPosX.Value + 30, _startPosY.Value), new Point(_startPosX.Value + 30, _startPosY.Value - 7), new Point(_startPosX.Value + 32, _startPosY.Value - 9), new Point(_startPosX.Value + 30, _startPosY.Value - 11), new Point(_startPosX.Value + 20, _startPosY.Value - 11), new Point(_startPosX.Value + 18, _startPosY.Value - 9), new Point(_startPosX.Value + 20, _startPosY.Value - 7), new Point(_startPosX.Value + 20, _startPosY.Value ) }; - g.FillPolygon(wheelBrush, points4); - } - - if (EntityLocomotive.Fueltank) - { - Point[] points5 = { new Point(_startPosX.Value + 52, _startPosY.Value + 50), new Point(_startPosX.Value + 92, _startPosY.Value + 50), new Point(_startPosX.Value + 87, _startPosY.Value + 35), new Point(_startPosX.Value + 57, _startPosY.Value + 35) }; - g.FillPolygon(wheelBrush, points5); - } - - if (EntityLocomotive.Headlight) - { - g.DrawLine(pen3, _startPosX.Value, _startPosY.Value - 5, _startPosX.Value + 15, _startPosY.Value ); - g.FillEllipse(headlightBrush, _startPosX.Value-2, _startPosY.Value - 6, 6, 14); - g.DrawEllipse(pen, _startPosX.Value-2 , _startPosY.Value - 6, 6, 14); - - } } -} +} \ No newline at end of file diff --git a/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningTLocomotive.cs b/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningTLocomotive.cs new file mode 100644 index 0000000..3b89bf4 --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/Drawnings/DrawningTLocomotive.cs @@ -0,0 +1,72 @@ +using System.Drawing.Drawing2D; +using ProjectLocomotive.Entities; + +namespace ProjectLocomotive.Drawnings +{ + public class DrawningTLocomotive : DrawningLocomotive + { + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия рогов + /// Признак наличия электрической батареи + /// Признак наличия фары + + public DrawningTLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool electro, bool headlight) + : base(150, 50) + { + EntityLocomotive = new EntityTLocomotive(speed, weight, bodyColor, additionalColor, horns, electro, headlight); + } + + public override void DrawTransport(Graphics g) + { + if (EntityLocomotive == null || EntityLocomotive is not EntityTLocomotive entityTLocomotive || !_startPosX.HasValue || + !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black, 2); + Pen pen2 = new(Color.White, 1); + Brush wheelBrush = new SolidBrush(Color.Black); + Brush wheelBrush2 = new SolidBrush(Color.Gray); + Brush headlightBrush = new SolidBrush(Color.Yellow); + Brush glassBrush = new SolidBrush(Color.Cyan); + Brush ElectroBrush = new HatchBrush(HatchStyle.ZigZag, entityTLocomotive.AdditionalColor, Color.FromArgb(163, 163, 163)); + Brush additionalBrush = new SolidBrush(entityTLocomotive.AdditionalColor); + Brush bodyBrush = new SolidBrush(EntityLocomotive.BodyColor); + + Point[] points = { new Point(_startPosX.Value + 5, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value + 20), new Point(_startPosX.Value, _startPosY.Value + 20) }; + g.FillPolygon(additionalBrush, points); + + base.DrawTransport(g); + + + + g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value, _startPosX.Value + 47, _startPosY.Value - 5); + g.DrawLine(pen, _startPosX.Value + 47, _startPosY.Value - 5, _startPosX.Value + 67, _startPosY.Value - 10); + g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value - 10, _startPosX.Value + 87, _startPosY.Value - 5); + g.DrawLine(pen, _startPosX.Value + 87, _startPosY.Value - 5, _startPosX.Value + 67, _startPosY.Value); + + + if (entityTLocomotive.Electro) + { + g.FillRectangle(ElectroBrush, _startPosX.Value + 107, _startPosY.Value - 5 + 3, 33, 28); + g.DrawRectangle(pen, _startPosX.Value + 107, _startPosY.Value - 5 + 3, 33, 28); + } + + if (entityTLocomotive.Headlight) + { + g.FillEllipse(headlightBrush, _startPosX.Value - 3, _startPosY.Value + 23, 6, 14); + g.DrawEllipse(pen, _startPosX.Value - 3, _startPosY.Value + 23, 6, 14); + + } + + } + } +} diff --git a/ProjectLocomotive/ProjectLocomotive/Entities/EntityLocomotiev.cs b/ProjectLocomotive/ProjectLocomotive/Entities/EntityLocomotiev.cs new file mode 100644 index 0000000..4e203a5 --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/Entities/EntityLocomotiev.cs @@ -0,0 +1,38 @@ +namespace ProjectLocomotive.Entities; + +/// +/// Класс-сущность "поед" +/// +public class EntityLocomotiev +{ + //свойства + /// + /// Скорость + /// + 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 EntityLocomotiev(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } +} diff --git a/ProjectLocomotive/ProjectLocomotive/Entities/EntityTLocomotive.cs b/ProjectLocomotive/ProjectLocomotive/Entities/EntityTLocomotive.cs new file mode 100644 index 0000000..43131b1 --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/Entities/EntityTLocomotive.cs @@ -0,0 +1,30 @@ +namespace ProjectLocomotive.Entities +{ + internal class EntityTLocomotive : EntityLocomotiev + { + /// + /// Признак (опция) наличие рогов + /// + public bool Horns { get; private set; } + /// + /// Признак (опция) наличие электробатареи + /// + public bool Electro { get; private set; } + /// + /// Признак (опция) наличие фары + /// + public bool Headlight { get; private set; } + /// + /// Дополнительный цвет (для опциональных элементов) + /// + public Color AdditionalColor { get; private set; } + + public EntityTLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool electro, bool headlight) : base(speed, weight, bodyColor) + { + AdditionalColor = additionalColor; + Horns = horns; + Electro = electro; + Headlight = headlight; + } + } +} diff --git a/ProjectLocomotive/ProjectLocomotive/EntityLocomotive.cs b/ProjectLocomotive/ProjectLocomotive/EntityLocomotive.cs deleted file mode 100644 index 79f4a27..0000000 --- a/ProjectLocomotive/ProjectLocomotive/EntityLocomotive.cs +++ /dev/null @@ -1,62 +0,0 @@ -namespace ProjectLocomotive; -/// -/// Класс-сущность "автобус" -/// -public class EntityLocomotive -{ - //свойства - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } - /// - /// Дополнительный цвет (для опциональных элементов) - /// - public Color AdditionalColor { get; private set; } - /// - /// Признак (опция) наличие рогов - /// - public bool Pipe { get; private set; } - /// - /// Признак (опция) наличие электрических батарей - /// - public bool Fueltank { get; private set; } - /// - /// Признак (опция) наличие фары - /// - public bool Headlight { get; private set; } - //поле класса - /// - /// Шаг перемещения автомобиля - /// - public double Step => Speed * 100 / Weight; - /// - /// Инициализация полей объекта-класса крейсера - /// - /// скорость - /// вес - /// основной цвет - /// дополнительный цвет - /// второй этаж - /// лестница - /// наличие фар - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool pipe, bool fueltank, bool headlight) - { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; - AdditionalColor = additionalColor; - Pipe = pipe; - Fueltank = fueltank; - Headlight = headlight; - } -} diff --git a/ProjectLocomotive/ProjectLocomotive/FormLocomotive.Designer.cs b/ProjectLocomotive/ProjectLocomotive/FormLocomotive.Designer.cs index 88e3a09..07139f9 100644 --- a/ProjectLocomotive/ProjectLocomotive/FormLocomotive.Designer.cs +++ b/ProjectLocomotive/ProjectLocomotive/FormLocomotive.Designer.cs @@ -1,5 +1,4 @@ - -namespace ProjectLocomotive +namespace ProjectLocomotive { partial class FormLocomotive { @@ -30,25 +29,28 @@ namespace ProjectLocomotive private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormLocomotive)); - pictureBox1 = new PictureBox(); + pictureBoxLocomotive = new PictureBox(); button1 = new Button(); buttonUp = new Button(); buttonDown = new Button(); buttonRight = new Button(); buttonLeft = new Button(); - ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); + comboBoxStrategy = new ComboBox(); + buttonCretaeLocomotive = new Button(); + buttonStrategyStep = new Button(); + ((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).BeginInit(); SuspendLayout(); // - // pictureBox1 + // pictureBoxLocomotive // - pictureBox1.Location = new Point(0, 0); - pictureBox1.Margin = new Padding(3, 2, 3, 2); - pictureBox1.Name = "pictureBox1"; - pictureBox1.Size = new Size(700, 338); - pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize; - pictureBox1.TabIndex = 0; - pictureBox1.TabStop = false; - pictureBox1.Click += pictureBox1_Click; + pictureBoxLocomotive.Dock = DockStyle.Fill; + pictureBoxLocomotive.Location = new Point(0, 0); + pictureBoxLocomotive.Margin = new Padding(3, 2, 3, 2); + pictureBoxLocomotive.Name = "pictureBoxLocomotive"; + pictureBoxLocomotive.Size = new Size(700, 338); + pictureBoxLocomotive.SizeMode = PictureBoxSizeMode.AutoSize; + pictureBoxLocomotive.TabIndex = 0; + pictureBoxLocomotive.TabStop = false; // // button1 // @@ -56,9 +58,9 @@ namespace ProjectLocomotive button1.Location = new Point(10, 307); button1.Margin = new Padding(3, 2, 3, 2); button1.Name = "button1"; - button1.Size = new Size(82, 22); + button1.Size = new Size(186, 22); button1.TabIndex = 1; - button1.Text = "создать"; + button1.Text = "создать электро-поезда"; button1.UseVisualStyleBackColor = true; button1.Click += ButtonCreateLocomotive_Click; // @@ -114,33 +116,74 @@ namespace ProjectLocomotive buttonLeft.UseVisualStyleBackColor = true; buttonLeft.Click += ButtonMove_Click; // + // comboBoxStrategy + // + comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right; + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "к центру", "к краю" }); + comboBoxStrategy.Location = new Point(557, 9); + comboBoxStrategy.Margin = new Padding(3, 2, 3, 2); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(133, 23); + comboBoxStrategy.TabIndex = 6; + // + // buttonCretaeLocomotive + // + buttonCretaeLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCretaeLocomotive.Location = new Point(210, 308); + buttonCretaeLocomotive.Margin = new Padding(3, 2, 3, 2); + buttonCretaeLocomotive.Name = "buttonCretaeLocomotive"; + buttonCretaeLocomotive.Size = new Size(186, 22); + buttonCretaeLocomotive.TabIndex = 7; + buttonCretaeLocomotive.Text = "создать поезда"; + buttonCretaeLocomotive.UseVisualStyleBackColor = true; + buttonCretaeLocomotive.Click += buttonCretaeLocomotive_Click; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(607, 34); + buttonStrategyStep.Margin = new Padding(3, 2, 3, 2); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(82, 22); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormLocomotive // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(700, 338); + Controls.Add(buttonStrategyStep); + Controls.Add(buttonCretaeLocomotive); + Controls.Add(comboBoxStrategy); Controls.Add(buttonLeft); Controls.Add(buttonRight); Controls.Add(buttonDown); Controls.Add(buttonUp); Controls.Add(button1); - Controls.Add(pictureBox1); + Controls.Add(pictureBoxLocomotive); Margin = new Padding(3, 2, 3, 2); Name = "FormLocomotive"; Text = "FormLocomotive"; Click += ButtonMove_Click; - ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); + ((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).EndInit(); ResumeLayout(false); PerformLayout(); } #endregion - private PictureBox pictureBox1; + private PictureBox pictureBoxLocomotive; private Button button1; private Button buttonUp; private Button buttonDown; private Button buttonRight; private Button buttonLeft; + private ComboBox comboBoxStrategy; + private Button buttonCretaeLocomotive; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectLocomotive/ProjectLocomotive/FormLocomotive.cs b/ProjectLocomotive/ProjectLocomotive/FormLocomotive.cs index 04f764f..f8bad3a 100644 --- a/ProjectLocomotive/ProjectLocomotive/FormLocomotive.cs +++ b/ProjectLocomotive/ProjectLocomotive/FormLocomotive.cs @@ -1,4 +1,7 @@ -namespace ProjectLocomotive +using ProjectLocomotive.Drawnings; +using ProjectLocomotive.MovementStrategy; + +namespace ProjectLocomotive { public partial class FormLocomotive : Form { @@ -6,14 +9,20 @@ /// Поле-объект для прорисовки объекта /// private DrawningLocomotive? _drawningLocomotive; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + public FormLocomotive() { InitializeComponent(); - + _strategy = null; } /// - /// Метод прорисовки поезда + /// Метод прорисовки круисера /// private void Draw() { @@ -21,35 +30,64 @@ { return; } - Bitmap bmp = new(pictureBox1.Width, - pictureBox1.Height); + Bitmap bmp = new(pictureBoxLocomotive.Width, + pictureBoxLocomotive.Height); Graphics gr = Graphics.FromImage(bmp); _drawningLocomotive.DrawTransport(gr); - pictureBox1.Image = bmp; + pictureBoxLocomotive.Image = bmp; } + /// - /// Обработка нажатия кнопки "Создать" + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawningLocomotive): + _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))); + break; + case nameof(DrawningTLocomotive): + _drawningLocomotive = new DrawningTLocomotive(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)), Convert.ToBoolean(random.Next(0, 2))); + break; + default: + return; + } + _drawningLocomotive.SetPictureSize(pictureBoxLocomotive.Width, + pictureBoxLocomotive.Height); + _drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } + + /// + /// Обработка нажатия кнопки "Создать военный крейсер" /// /// /// - private void ButtonCreateLocomotive_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningLocomotive = new DrawningLocomotive(); - _drawningLocomotive.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)), Convert.ToBoolean(random.Next(0, 2))); - _drawningLocomotive.SetPictureSize(pictureBox1.Width, - pictureBox1.Height); + private void ButtonCreateLocomotive_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTLocomotive)); + + /// + /// Обработка нажатия кнопки "Создать крейсер" + /// + /// + /// + private void buttonCretaeLocomotive_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningLocomotive)); + - //начальное положение поезда - _drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); - Draw(); - } /// /// Перемещение объекта по форме (нажатие кнопок навигации) /// @@ -88,9 +126,49 @@ } } - private void pictureBox1_Click(object sender, EventArgs e) + /// + /// обработка нажатия кнопки шаг + /// + /// + /// + private void ButtonStrategyStep_Click(object sender, EventArgs e) { + if (_drawningLocomotive == null) + { + return; + } + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableLocomotive(_drawningLocomotive), pictureBoxLocomotive.Width, pictureBoxLocomotive.Height); + } + + if (_strategy == null) + { + return; + } + + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } } + } } diff --git a/ProjectLocomotive/ProjectLocomotive/MovementStrategy/AbstractStrategy.cs b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..e9efc63 --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,123 @@ +namespace ProjectLocomotive.MovementStrategy +{ + /// + /// Класс-стратегия перемещения объекта + /// + public abstract class AbstractStrategy + { + /// + /// Перемещаемый объект + /// + 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/ProjectLocomotive/ProjectLocomotive/MovementStrategy/IMoveableObject.cs b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..6b4f09b --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,24 @@ +namespace ProjectLocomotive.MovementStrategy +{ + /// + /// Интерфейс для работы с перемещаемым объектом + /// + public interface IMoveableObject + { + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); + } + +} diff --git a/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveToBorder.cs b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..8e8e846 --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,53 @@ +namespace ProjectLocomotive.MovementStrategy +{ + /// + /// Стратегия перемещения объекта к краю экрана + /// + internal class MoveToBorder : AbstractStrategy + { + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.RightBorder - GetStep() <= FieldWidth + && objParams.RightBorder + GetStep() >= FieldWidth && + objParams.DownBorder - GetStep() <= 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/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveToCenter.cs b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..120a07f --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,53 @@ +namespace ProjectLocomotive.MovementStrategy +{ + /// + /// Стратегия перемещения объекта в центр экрана + /// + public class MoveToCenter : AbstractStrategy + { + 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/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveableTrain.cs b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveableTrain.cs new file mode 100644 index 0000000..2bbd26a --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MoveableTrain.cs @@ -0,0 +1,62 @@ +using ProjectLocomotive.Drawnings; + +namespace ProjectLocomotive.MovementStrategy +{ + /// + /// класс реалтзация для IMoveableObject с использованием DrawningLocomotive + /// + public class MoveableLocomotive : IMoveableObject + { + /// + /// Поле-объект класса DrawningLocomotive или его наследника + /// + private readonly DrawningLocomotive? _cruiser = null; + /// + /// Конструктор + /// + /// Объект класса DrawningLocomotive + public MoveableLocomotive(DrawningLocomotive cruiser) + { + _cruiser = cruiser; + } + public ObjectParameters? GetObjectPosition + { + get + { + if (_cruiser == null || _cruiser.EntityLocomotive == null || + !_cruiser.GetPosX.HasValue || !_cruiser.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_cruiser.GetPosX.Value, + _cruiser.GetPosY.Value, _cruiser.GetWidth, _cruiser.GetHeight); + } + } + public int GetStep => (int)(_cruiser?.EntityLocomotive?.Step ?? 0); + public bool TryMoveObject(MovementDirection direction) + { + if (_cruiser == null || _cruiser.EntityLocomotive == null) + { + return false; + } + return _cruiser.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/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MovementDirection.cs b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..1a8f8ff --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/MovementDirection.cs @@ -0,0 +1,26 @@ +namespace ProjectLocomotive.MovementStrategy +{ + /// + /// Направление перемещения + /// + public enum MovementDirection + { + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 + } + +} diff --git a/ProjectLocomotive/ProjectLocomotive/MovementStrategy/ObjectParameters.cs b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..0cf30d9 --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,64 @@ +namespace ProjectLocomotive.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/ProjectLocomotive/ProjectLocomotive/MovementStrategy/StrategyStatus.cs b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..eec0e3b --- /dev/null +++ b/ProjectLocomotive/ProjectLocomotive/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,22 @@ +namespace ProjectLocomotive.MovementStrategy +{ + /// + /// Статус выполнения операции перемещения + /// + public enum StrategyStatus + { + /// + /// Все готово к началу + /// + NotInit, + /// + /// Выполняется + /// + InProgress, + /// + /// Завершено + /// + Finish + } + +}