diff --git a/ProjectCatamaran/ProjectCatamaran/DrawningCatamaran.cs b/ProjectCatamaran/ProjectCatamaran/DrawningCatamaran.cs deleted file mode 100644 index 5a01c1b..0000000 --- a/ProjectCatamaran/ProjectCatamaran/DrawningCatamaran.cs +++ /dev/null @@ -1,217 +0,0 @@ -namespace ProjectCatamaran; - -/// -/// Класс, отвечающий за прорисовку и перемещение объекта-сущности -/// -public class DrawningCatamaran -{ - /// - /// Класс-сущность - /// - public EntityCatamaran? EntityCatamaran { get; private set; } - - /// - /// Ширина окна - /// - private int? _pictureWidth; - - /// - /// Высота окна - /// - private int? _pictureHeight; - - /// - /// Левая координата прорисовки катамарана - /// - private int? _startPosX; - - /// - /// Верхняя координата прорисовки катамарана - /// - private int? _startPosY; - - /// - /// Ширина прорисовки катамарана - /// - private readonly int _drawningCatamaranWidth = 87; - - /// - /// Высота прорисовки катамарана - /// - private readonly int _drawningCatamaranHeight = 81; - - /// - /// Инициализация свойств - /// - /// - /// - /// - /// - /// - /// - /// - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool sail, - bool leftfloater, bool rightfloater) - { - EntityCatamaran = new EntityCatamaran(); - EntityCatamaran.Init(speed, weight, bodyColor, additionalColor, sail, leftfloater, rightfloater); - _pictureWidth = null; - _pictureHeight = null; - _startPosX = null; - _startPosY = null; - } - - /// - /// Установка границ поля - /// - /// Ширина поля - /// Вершина поля - /// - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах - public bool SetPictureSize(int width, int height) - { - if (_drawningCatamaranHeight > height || _drawningCatamaranWidth > width) - { - return false; - } - - _pictureWidth = width; - _pictureHeight = height; - - if (_startPosX.HasValue && _startPosY.HasValue) - { - SetPosition(_startPosX.Value, _startPosY.Value); - } - - return true; - } - - - /// - /// Установка позиции - /// - /// Координаты Х - /// Координаты Y - public void SetPosition(int x, int y) - { - if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) - { - return; - } - - if (x < 0 || x + _drawningCatamaranWidth > _pictureWidth || y < 0 || y + _drawningCatamaranHeight > _pictureHeight) - { - _startPosX = _pictureWidth - _drawningCatamaranWidth; - _startPosY = _pictureHeight - _drawningCatamaranHeight; - } - else - { - _startPosX = x; - _startPosY = y; - } - } - - /// - /// Изменение направления перемещения - /// - /// Направление - /// - перемещение выполнено, false - перемещение невозможно - public bool MoveTransport(DirectionType direction) - { - if (EntityCatamaran == null || !_startPosX.HasValue || !_startPosY.HasValue) - { - return false; - } - switch (direction) - { - //влево - case DirectionType.Left: - if (_startPosX.Value - EntityCatamaran.Step > 0) - { - _startPosX -= (int)EntityCatamaran.Step; - } - return true; - //вверх - case DirectionType.Up: - if (_startPosY.Value - EntityCatamaran.Step > 0) - { - _startPosY -= (int)EntityCatamaran.Step; - } - return true; - // вправо - case DirectionType.Right: - if (_startPosX.Value + EntityCatamaran.Step + _drawningCatamaranWidth < _pictureWidth) - { - _startPosX += (int)EntityCatamaran.Step; - return true; - } - return true; - //вниз - case DirectionType.Down: - if (_startPosY.Value + EntityCatamaran.Step + _drawningCatamaranHeight < _pictureHeight) - { - _startPosY += (int)EntityCatamaran.Step; - } - return true; - default: - return false; - } - } - - /// - /// Прорисовка объекта - /// - /// - public void DrawTransport(Graphics g) - { - if (EntityCatamaran == null || !_startPosX.HasValue || !_startPosY.HasValue) - { - return; - } - - Pen pen = new(Color.Black); - Brush bodyColorBrush = new SolidBrush(EntityCatamaran.BodyColor); - Brush additionalBrush = new SolidBrush(EntityCatamaran.AdditionalColor); - - //тело катамарана - g.FillRectangle(bodyColorBrush, _startPosX.Value + 10, _startPosY.Value + 40, 57, 30); - g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 40, 57, 30); - - g.FillEllipse(bodyColorBrush, _startPosX.Value + 20, _startPosY.Value + 48, 40, 13); - g.DrawEllipse(pen, _startPosX.Value + 20, _startPosY.Value + 48, 40, 13); - - //нос катамарана - Point[] Nose = new Point[3]; - Nose[0].X = _startPosX.Value + 67; Nose[0].Y = _startPosY.Value + 40; - Nose[1].X = _startPosX.Value + 88; Nose[1].Y = _startPosY.Value + 55; - Nose[2].X = _startPosX.Value + 67; Nose[2].Y = _startPosY.Value + 70; - g.FillPolygon(bodyColorBrush, Nose); - g.DrawPolygon(pen, Nose); - - //поплавки - if (EntityCatamaran.Leftfloater) - { - g.FillEllipse(additionalBrush, _startPosX.Value + 10, _startPosY.Value + 27, 57, 13); - g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 27, 57, 13); - } - - if (EntityCatamaran.Rightfloater) - { - g.FillEllipse(additionalBrush, _startPosX.Value + 10, _startPosY.Value + 70, 57, 13); - g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 70, 57, 13); - } - - //флаг - if (EntityCatamaran.Sail) - { - g.DrawLine(pen, _startPosX.Value + 38, _startPosY.Value + 55, _startPosX.Value + 38, _startPosY.Value + 10); - Point[] Flag = new Point[3]; - Flag[0].X = _startPosX.Value + 38; Flag[0].Y = _startPosY.Value + 10; - Flag[1].X = _startPosX.Value + 55; Flag[1].Y = _startPosY.Value + 45; - Flag[2].X = _startPosX.Value + 38; Flag[2].Y = _startPosY.Value + 45; - g.FillPolygon(additionalBrush, Flag); - g.DrawPolygon(pen, Flag); - } - } - - -} diff --git a/ProjectCatamaran/ProjectCatamaran/Drawnings/DirectionType.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/DirectionType.cs new file mode 100644 index 0000000..f1a237c --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/DirectionType.cs @@ -0,0 +1,30 @@ +namespace ProjectCatamaran.Drawnings; + +public enum DirectionType +{ + /// + /// Неизвестное направление + /// + Unknow = -1, + + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 + +} diff --git a/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoat.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoat.cs new file mode 100644 index 0000000..14a33d9 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoat.cs @@ -0,0 +1,234 @@ +using ProjectCatamaran.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Drawnings; + +/// +/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности +/// +public class DrawningBoat +{ + /// + /// Класс-сущность + /// + public EntityBoat? EntityBoat { get; protected set; } + + /// + /// Ширина окна + /// + private int? _pictureWidth; + + /// + /// Высота окна + /// + private int? _pictureHeight; + + /// + /// Левая координата прорисовки катамарана + /// + protected int? _startPosX; + + /// + /// Верхняя координата прорисовки катамарана + /// + protected int? _startPosY; + + /// + /// Ширина прорисовки катамарана + /// + private readonly int _drawningBoatWidth = 80; + + /// + /// Высота прорисовки катамарана + /// + private readonly int _drawningBoatHeight = 80; + + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _drawningBoatWidth; + /// + /// Высота объекта + /// + public int GetHeight => _drawningBoatHeight; + + /// + /// Пустой конструктор + /// + private DrawningBoat() + { + _pictureWidth = null; + _pictureHeight = null; + _startPosX = null; + _startPosY = null; + } + /// + /// Конструктор + /// + /// + /// + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки катамарана + /// Высота прорисовки катамарана + protected DrawningBoat(int drawningCatamaranWidth, int drawningCatamaranHeight) : this() + { + _drawningBoatWidth = drawningCatamaranWidth; + _pictureHeight = drawningCatamaranHeight; + } + + + /// + /// Установка границ поля + /// + /// Ширина поля + /// Вершина поля + /// - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах + public bool SetPictureSize(int width, int height) + { + if (_drawningBoatHeight > height || _drawningBoatWidth > width) + { + return false; + } + + _pictureWidth = width; + _pictureHeight = height; + + if (_startPosX.HasValue && _startPosY.HasValue) + { + SetPosition(_startPosX.Value, _startPosY.Value); + } + + return true; + } + + + /// + /// Установка позиции + /// + /// Координаты Х + /// Координаты Y + public void SetPosition(int x, int y) + { + if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) + { + return; + } + + if (x < 0 || x + _drawningBoatWidth > _pictureWidth) + { + _startPosX = _pictureWidth - _drawningBoatWidth; + } + else + { + _startPosX = x; + } + + if (y < 0 || y + _drawningBoatHeight > _pictureHeight) + { + _startPosY = _pictureHeight - _drawningBoatHeight; + } + else + { + _startPosY = y; + } + } + + /// + /// Изменение направления перемещения + /// + /// Направление + /// - перемещение выполнено, false - перемещение невозможно + public bool MoveTransport(DirectionType direction) + { + if (EntityBoat == null || !_startPosX.HasValue || !_startPosY.HasValue) + { + return false; + } + switch (direction) + { + //влево + case DirectionType.Left: + if (_startPosX.Value - EntityBoat.Step > 0) + { + _startPosX -= (int)EntityBoat.Step; + } + return true; + //вверх + case DirectionType.Up: + if (_startPosY.Value - EntityBoat.Step > 0) + { + _startPosY -= (int)EntityBoat.Step; + } + return true; + // вправо + case DirectionType.Right: + if (_startPosX.Value + EntityBoat.Step + _drawningBoatWidth < _pictureWidth) + { + _startPosX += (int)EntityBoat.Step; + return true; + } + return true; + //вниз + case DirectionType.Down: + if (_startPosY.Value + EntityBoat.Step + _drawningBoatHeight < _pictureHeight) + { + _startPosY += (int)EntityBoat.Step; + } + return true; + default: + return false; + } + } + + /// + /// Прорисовка объекта + /// + /// + public virtual void DrawTransport(Graphics g) + { + if (EntityBoat == null || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black); + Brush bodyColorBrush = new SolidBrush(EntityBoat.BodyColor); + + //тело катамарана + g.FillRectangle(bodyColorBrush, _startPosX.Value, _startPosY.Value + 32, 57, 30); + g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 32, 57, 30); + + g.FillEllipse(bodyColorBrush, _startPosX.Value + 9, _startPosY.Value + 40, 40, 13); + g.DrawEllipse(pen, _startPosX.Value + 9, _startPosY.Value + 40, 40, 13); + + //нос катамарана + Point[] Nose = new Point[3]; + Nose[0].X = _startPosX.Value + 57; Nose[0].Y = _startPosY.Value + 32; + Nose[1].X = _startPosX.Value + 80; Nose[1].Y = _startPosY.Value + 47; + Nose[2].X = _startPosX.Value + 57; Nose[2].Y = _startPosY.Value + 62; + g.FillPolygon(bodyColorBrush, Nose); + g.DrawPolygon(pen, Nose); + + } +} diff --git a/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningCatamaran.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningCatamaran.cs new file mode 100644 index 0000000..40f166f --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningCatamaran.cs @@ -0,0 +1,65 @@ +using ProjectCatamaran.Entities; + +namespace ProjectCatamaran.Drawnings; + +/// +/// Класс, отвечающий за прорисовку и перемещение объекта-сущности +/// +public class DrawningCatamaran : DrawningBoat +{ + + /// + /// Конструктор + /// + /// + /// + /// + /// + /// + /// + /// + public DrawningCatamaran(int speed, double weight, Color bodyColor, Color additionalColor, bool sail, bool leftfloater, bool rightfloater) : base(80, 80) + { + EntityBoat = new EntityCatamaran(speed, weight, bodyColor, additionalColor, sail, leftfloater, rightfloater); + + } + + + public override void DrawTransport(Graphics g) + { + if (EntityBoat == null || EntityBoat is not EntityCatamaran catamaran || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black); + Brush additionalBrush = new SolidBrush(catamaran.AdditionalColor); + base.DrawTransport(g); + //поплавки + if (catamaran.Leftfloater) + { + g.FillEllipse(additionalBrush, _startPosX.Value, _startPosY.Value + 20, 57, 13); + g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 20, 57, 13); + } + + if (catamaran.Rightfloater) + { + g.FillEllipse(additionalBrush, _startPosX.Value, _startPosY.Value + 62, 57, 13); + g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 62, 57, 13); + } + + //флаг + if (catamaran.Sail) + { + g.DrawLine(pen, _startPosX.Value + 29, _startPosY.Value + 48, _startPosX.Value + 29, _startPosY.Value); + Point[] Flag = new Point[3]; + Flag[0].X = _startPosX.Value + 29; Flag[0].Y = _startPosY.Value + 38; + Flag[1].X = _startPosX.Value + 48; Flag[1].Y = _startPosY.Value + 38; + Flag[2].X = _startPosX.Value + 29; Flag[2].Y = _startPosY.Value; + g.FillPolygon(additionalBrush, Flag); + g.DrawPolygon(pen, Flag); + } + } + + +} diff --git a/ProjectCatamaran/ProjectCatamaran/Entities/EntityBoat.cs b/ProjectCatamaran/ProjectCatamaran/Entities/EntityBoat.cs new file mode 100644 index 0000000..1cc8f3f --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Entities/EntityBoat.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Entities; + +/// +/// Класс-сущности "Лодка" +/// +public class EntityBoat +{ + /// + /// Скорость + /// + 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 EntityBoat(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } +} diff --git a/ProjectCatamaran/ProjectCatamaran/EntityCatamaran.cs b/ProjectCatamaran/ProjectCatamaran/Entities/EntityCatamaran.cs similarity index 67% rename from ProjectCatamaran/ProjectCatamaran/EntityCatamaran.cs rename to ProjectCatamaran/ProjectCatamaran/Entities/EntityCatamaran.cs index 25affe6..57ebd06 100644 --- a/ProjectCatamaran/ProjectCatamaran/EntityCatamaran.cs +++ b/ProjectCatamaran/ProjectCatamaran/Entities/EntityCatamaran.cs @@ -1,24 +1,10 @@ -namespace ProjectCatamaran; +namespace ProjectCatamaran.Entities; /// /// Класс-сущность "Катамаран" /// -public class EntityCatamaran +public class EntityCatamaran : EntityBoat { - /// - /// Скорость - /// - public int Speed { get; private set; } - - /// - /// Вес - /// - public double Weight { get; private set; } - - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } /// /// Дополнительный цвет (для опциональных элементов) @@ -40,14 +26,9 @@ public class EntityCatamaran /// public bool Sail { get; private set; } - /// - /// - /// - public double Step => Speed * 100 / Weight; - /// - /// + /// Инициализация полей объекта-класса катамарана /// /// Скорость /// Вес @@ -56,11 +37,8 @@ public class EntityCatamaran /// Признак наличия левого поплавка /// Признак наличия правого поплавка /// Признак наличия паруса - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool leftfloater, bool rightfloater, bool sail) + public EntityCatamaran(int speed, double weight, Color bodyColor, Color additionalColor, bool leftfloater, bool rightfloater, bool sail) : base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; AdditionalColor = additionalColor; Leftfloater = leftfloater; Rightfloater = rightfloater; diff --git a/ProjectCatamaran/ProjectCatamaran/FormCatamaran.Designer.cs b/ProjectCatamaran/ProjectCatamaran/FormCatamaran.Designer.cs index e1650d2..bc91fa0 100644 --- a/ProjectCatamaran/ProjectCatamaran/FormCatamaran.Designer.cs +++ b/ProjectCatamaran/ProjectCatamaran/FormCatamaran.Designer.cs @@ -34,6 +34,9 @@ buttonLeft = new Button(); buttonDown = new Button(); buttonRight = new Button(); + buttonCreatBoat = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxCatamaran).BeginInit(); SuspendLayout(); // @@ -45,16 +48,15 @@ pictureBoxCatamaran.Size = new Size(800, 450); pictureBoxCatamaran.TabIndex = 0; pictureBoxCatamaran.TabStop = false; - pictureBoxCatamaran.Click += ButtonMove_Click; // // buttonCreateCatamaran // buttonCreateCatamaran.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateCatamaran.Location = new Point(12, 409); buttonCreateCatamaran.Name = "buttonCreateCatamaran"; - buttonCreateCatamaran.Size = new Size(94, 29); + buttonCreateCatamaran.Size = new Size(203, 29); buttonCreateCatamaran.TabIndex = 1; - buttonCreateCatamaran.Text = "Создать"; + buttonCreateCatamaran.Text = "Создать катамаран"; buttonCreateCatamaran.UseVisualStyleBackColor = true; buttonCreateCatamaran.Click += ButtonCreateCatamaran_Click; // @@ -108,11 +110,45 @@ buttonRight.UseVisualStyleBackColor = false; buttonRight.Click += ButtonMove_Click; // + // buttonCreatBoat + // + buttonCreatBoat.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreatBoat.Location = new Point(233, 409); + buttonCreatBoat.Name = "buttonCreatBoat"; + buttonCreatBoat.Size = new Size(203, 29); + buttonCreatBoat.TabIndex = 6; + buttonCreatBoat.Text = "Создать лодку"; + buttonCreatBoat.UseVisualStyleBackColor = true; + buttonCreatBoat.Click += ButtonCreatBoat_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(653, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(135, 28); + comboBoxStrategy.TabIndex = 8; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(694, 46); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(94, 29); + buttonStrategyStep.TabIndex = 9; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormCatamaran // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(800, 450); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreatBoat); Controls.Add(buttonRight); Controls.Add(buttonDown); Controls.Add(buttonLeft); @@ -133,5 +169,8 @@ private Button buttonLeft; private Button buttonDown; private Button buttonRight; + private Button buttonCreatBoat; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectCatamaran/ProjectCatamaran/FormCatamaran.cs b/ProjectCatamaran/ProjectCatamaran/FormCatamaran.cs index 507fc01..8b7a425 100644 --- a/ProjectCatamaran/ProjectCatamaran/FormCatamaran.cs +++ b/ProjectCatamaran/ProjectCatamaran/FormCatamaran.cs @@ -7,6 +7,8 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using ProjectCatamaran.Drawnings; +using ProjectCatamaran.MovementStrategy; namespace ProjectCatamaran { @@ -15,7 +17,13 @@ namespace ProjectCatamaran /// /// Поле-объект для прорисовки объекта /// - private DrawningCatamaran? _drawningCatamaran; + private DrawningBoat? _drawningBoat; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + /// /// Конструктор формы @@ -23,42 +31,68 @@ namespace ProjectCatamaran public FormCatamaran() { InitializeComponent(); + _strategy = null; } + /// + /// Создание объекта класса-перемещения + /// + /// + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawningBoat): + _drawningBoat = new DrawningBoat(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(DrawningCatamaran): + _drawningBoat = new DrawningCatamaran(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; + } + _drawningBoat.SetPictureSize(pictureBoxCatamaran.Width, pictureBoxCatamaran.Height); + _drawningBoat.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } /// - /// Обработка нажатия кнопки "Создать" + /// Обработка нажатия кнопки "Создать катамаран" /// /// /// - private void ButtonCreateCatamaran_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningCatamaran = new DrawningCatamaran(); - _drawningCatamaran.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))); - _drawningCatamaran.SetPictureSize(pictureBoxCatamaran.Width, pictureBoxCatamaran.Height); - _drawningCatamaran.SetPosition(random.Next(10, 100), random.Next(10, 100)); - Draw(); + private void ButtonCreateCatamaran_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningCatamaran)); - } + + /// + /// Обработка нажатия кнопки "Создать лодку" + /// + /// + /// + private void ButtonCreatBoat_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBoat)); /// /// Метод прорисовки катамарана /// private void Draw() { - if (_drawningCatamaran == null) + if (_drawningBoat == null) { return; } Bitmap bmp = new(pictureBoxCatamaran.Width, pictureBoxCatamaran.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningCatamaran.DrawTransport(gr); + _drawningBoat.DrawTransport(gr); pictureBoxCatamaran.Image = bmp; } @@ -70,7 +104,7 @@ namespace ProjectCatamaran private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningCatamaran == null) + if (_drawningBoat == null) { return; } @@ -79,16 +113,16 @@ namespace ProjectCatamaran switch (name) { case "buttonUp": - result = _drawningCatamaran.MoveTransport(DirectionType.Up); + result = _drawningBoat.MoveTransport(DirectionType.Up); break; case "buttonDown": - result = _drawningCatamaran.MoveTransport(DirectionType.Down); + result = _drawningBoat.MoveTransport(DirectionType.Down); break; case "buttonLeft": - result = _drawningCatamaran.MoveTransport(DirectionType.Left); + result = _drawningBoat.MoveTransport(DirectionType.Left); break; case "buttonRight": - result = _drawningCatamaran.MoveTransport(DirectionType.Right); + result = _drawningBoat.MoveTransport(DirectionType.Right); break; } if (result) @@ -97,5 +131,48 @@ namespace ProjectCatamaran } } + /// + /// обработка нажатия кнопки шаг + /// + /// + /// + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningBoat == null) + { + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + + if (_strategy == null) + { + return; + } + _strategy.SetData(new MovebleBoat(_drawningBoat), pictureBoxCatamaran.Width, pictureBoxCatamaran.Height); + } + + if (_strategy == null) + { + return; + } + + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } } } diff --git a/ProjectCatamaran/ProjectCatamaran/MovementStrategy/AbstractStrategy.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..394eab7 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.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/ProjectCatamaran/ProjectCatamaran/MovementStrategy/IMoveableObject.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..969fa2e --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.MovementStrategy; + +/// +/// Интерфейс для работы с перемещаемым объектом +/// +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveToBorder.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..9208068 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.MovementStrategy; + +public 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/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveToCenter.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..ae5a690 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.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/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MovebleBoat.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MovebleBoat.cs new file mode 100644 index 0000000..11ba420 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MovebleBoat.cs @@ -0,0 +1,62 @@ +using ProjectCatamaran.Drawnings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.MovementStrategy; + +public class MovebleBoat : IMoveableObject +{ + /// + /// Поле-объект класса DrawningBoat или его наследника + /// + private readonly DrawningBoat? _boat = null; + /// + /// Конструктор + /// + /// Объект класса DrawningBoat + public MovebleBoat(DrawningBoat boat) + { + _boat = boat; + } + public ObjectParameters? GetObjectPosition + { + get + { + if (_boat == null || _boat.EntityBoat == null || + !_boat.GetPosX.HasValue || !_boat.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_boat.GetPosX.Value, + _boat.GetPosY.Value, _boat.GetWidth, _boat.GetHeight); + } + } + public int GetStep => (int)(_boat?.EntityBoat?.Step ?? 0); + public bool TryMoveObject(MovementDirection direction) + { + if (_boat == null || _boat.EntityBoat == null) + { + return false; + } + return _boat.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/ProjectCatamaran/ProjectCatamaran/DirectionType.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MovementDirection.cs similarity index 72% rename from ProjectCatamaran/ProjectCatamaran/DirectionType.cs rename to ProjectCatamaran/ProjectCatamaran/MovementStrategy/MovementDirection.cs index f76939e..47cf476 100644 --- a/ProjectCatamaran/ProjectCatamaran/DirectionType.cs +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MovementDirection.cs @@ -4,9 +4,12 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ProjectCatamaran; +namespace ProjectCatamaran.MovementStrategy; -public enum DirectionType +/// +/// Направление перемещения +/// +public enum MovementDirection { /// /// Вверх @@ -27,5 +30,4 @@ public enum DirectionType /// Вправо /// Right = 4 - } diff --git a/ProjectCatamaran/ProjectCatamaran/MovementStrategy/ObjectParameters.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..7c50ff0 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.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/ProjectCatamaran/ProjectCatamaran/MovementStrategy/StrategyStatus.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..cc85dcf --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +} diff --git a/ProjectCatamaran/ProjectCatamaran/Program.cs b/ProjectCatamaran/ProjectCatamaran/Resources/Program.cs similarity index 92% rename from ProjectCatamaran/ProjectCatamaran/Program.cs rename to ProjectCatamaran/ProjectCatamaran/Resources/Program.cs index 4d620b5..89a0c0b 100644 --- a/ProjectCatamaran/ProjectCatamaran/Program.cs +++ b/ProjectCatamaran/ProjectCatamaran/Resources/Program.cs @@ -1,4 +1,4 @@ -namespace ProjectCatamaran +namespace ProjectCatamaran.Resources { internal static class Program {