From a8c4022a95fda33d6cedd26a254a4cdd41165c15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=B7=D0=B0=D0=BC=D0=B0=D1=82=20=D0=98=D1=88=D1=82?= =?UTF-8?q?=D1=83=D0=B3=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Mon, 11 Mar 2024 00:47:28 +0400 Subject: [PATCH 1/2] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=80=D0=BE=D0=B4=D0=B8=D1=82=D0=B5=D0=BB?= =?UTF-8?q?=D0=B5=D0=B9=20=D0=B8=20=D0=B2=D0=B2=D0=BE=D0=B4=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BD=D1=81=D1=82=D1=80=D1=83=D0=BA=D1=82=D0=BE=D1=80=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{ => Drawnings}/DirectionType.cs | 2 +- .../DrawningBoat.cs} | 134 ++++++++---------- .../MotorBoat/Drawnings/DrawningMotorBoat.cs | 65 +++++++++ MotorBoat/MotorBoat/Entities/EntityBoat.cs | 43 ++++++ .../{ => Entities}/EntityMotorBoat.cs | 23 +-- MotorBoat/MotorBoat/FormMotorBoat.Designer.cs | 38 +++-- MotorBoat/MotorBoat/FormMotorBoat.cs | 63 ++++---- 7 files changed, 241 insertions(+), 127 deletions(-) rename MotorBoat/MotorBoat/{ => Drawnings}/DirectionType.cs (93%) rename MotorBoat/MotorBoat/{DrawningMotorBoat.cs => Drawnings/DrawningBoat.cs} (57%) create mode 100644 MotorBoat/MotorBoat/Drawnings/DrawningMotorBoat.cs create mode 100644 MotorBoat/MotorBoat/Entities/EntityBoat.cs rename MotorBoat/MotorBoat/{ => Entities}/EntityMotorBoat.cs (70%) diff --git a/MotorBoat/MotorBoat/DirectionType.cs b/MotorBoat/MotorBoat/Drawnings/DirectionType.cs similarity index 93% rename from MotorBoat/MotorBoat/DirectionType.cs rename to MotorBoat/MotorBoat/Drawnings/DirectionType.cs index b735a41..7a584f2 100644 --- a/MotorBoat/MotorBoat/DirectionType.cs +++ b/MotorBoat/MotorBoat/Drawnings/DirectionType.cs @@ -1,4 +1,4 @@ -namespace MotorBoat +namespace MotorBoat.Drawnings { /// diff --git a/MotorBoat/MotorBoat/DrawningMotorBoat.cs b/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs similarity index 57% rename from MotorBoat/MotorBoat/DrawningMotorBoat.cs rename to MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs index 47cbe84..f25e29b 100644 --- a/MotorBoat/MotorBoat/DrawningMotorBoat.cs +++ b/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs @@ -1,14 +1,18 @@ -namespace MotorBoat +using MotorBoat.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.Drawnings { - /// - /// Класс, отвечающий за прорисовку и перемещение объекта-сущности - /// - public class DrawningMotorBoat + public class DrawningBoat { /// /// Класс-сущность /// - public EntityMotorBoat? EntityMotorBoat { get; private set; } + public EntityBoat? EntityBoat { get; protected set; } /// /// Ширина окна /// @@ -20,39 +24,51 @@ /// /// Левая координата прорисовки лодки /// - private int? _startPosX; + protected int? _startPosX; /// /// Верхняя кооридната прорисовки лодки /// - private int? _startPosY; + protected int? _startPosY; /// /// Ширина прорисовки лодки /// - private readonly int _drawningBoatWidth = 153; + private readonly int _drawningBoatWidth = 143; /// /// Высота прорисовки лодки /// - private readonly int _drawningBoatHeight = 75; + private readonly int _drawningBoatHeight = 38; /// - /// Инициализация свойств + /// Пустой конструктор /// - /// Скорость - /// Вес - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия защитного стекла - /// Признак наличия мотора - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, - bool protectiveGlass, bool engine) + private DrawningBoat() { - EntityMotorBoat = new EntityMotorBoat(); - EntityMotorBoat.Init(speed, weight, bodyColor, additionalColor, protectiveGlass, engine); _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + public DrawningBoat(int speed, double weight, Color bodyColor) : this() + { + EntityBoat = new EntityBoat(speed, weight, bodyColor); + } + + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки лодки + /// Высота прорисовки лодки + protected DrawningBoat(int drawningBoatWidth, int drawningBoatHeight) : this() + { + _drawningBoatWidth = drawningBoatWidth; + _drawningBoatHeight = drawningBoatHeight; + } + /// /// Установка границ поля /// /// Ширина поля @@ -68,10 +84,10 @@ if (_startPosX != null && _startPosY != null) { if (_startPosX.Value < 0) - { + { _startPosX = 0; } - if (_startPosY.Value < 0) + if (_startPosY.Value < 0) { _startPosY = 0; } @@ -126,7 +142,7 @@ /// невозможно public bool MoveTransport(DirectionType direction) { - if (EntityMotorBoat == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityBoat == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; } @@ -134,30 +150,30 @@ { //влево case DirectionType.Left: - if (_startPosX.Value - EntityMotorBoat.Step > 0) + if (_startPosX.Value - EntityBoat.Step > 0) { - _startPosX -= (int)EntityMotorBoat.Step; + _startPosX -= (int)EntityBoat.Step; } return true; //вверх case DirectionType.Up: - if (_startPosY.Value - EntityMotorBoat.Step > 0) + if (_startPosY.Value - EntityBoat.Step > 0) { - _startPosY -= (int)EntityMotorBoat.Step; + _startPosY -= (int)EntityBoat.Step; } return true; //вправо case DirectionType.Right: - if (_startPosX.Value + _drawningBoatWidth + EntityMotorBoat.Step < _pictureWidth) + if (_startPosX.Value + _drawningBoatWidth + EntityBoat.Step < _pictureWidth) { - _startPosX += (int)EntityMotorBoat.Step; + _startPosX += (int)EntityBoat.Step; } return true; //вниз case DirectionType.Down: - if (_startPosY.Value + _drawningBoatHeight + EntityMotorBoat.Step < _pictureHeight) + if (_startPosY.Value + _drawningBoatHeight + EntityBoat.Step < _pictureHeight) { - _startPosY += (int)EntityMotorBoat.Step; + _startPosY += (int)EntityBoat.Step; } return true; default: @@ -169,26 +185,25 @@ /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { - if (EntityMotorBoat == null || !_startPosX.HasValue || + if (EntityBoat == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } Pen pen = new(Color.Black); - Brush brushBodyColor = new SolidBrush(EntityMotorBoat.BodyColor); - Brush brushAdditionalColor = new SolidBrush(EntityMotorBoat.AdditionalColor); + Brush brushBodyColor = new SolidBrush(EntityBoat.BodyColor); - Point[] body = + Point[] body = { - new Point(_startPosX.Value + 10, _startPosY.Value + 25), - new Point(_startPosX.Value + 110, _startPosY.Value + 25), - new Point(_startPosX.Value + 155, _startPosY.Value + 45), - new Point(_startPosX.Value + 110, _startPosY.Value + 65), - new Point(_startPosX.Value + 10, _startPosY.Value + 65), - new Point(_startPosX.Value + 10, _startPosY.Value + 25) + new Point(_startPosX.Value, _startPosY.Value), + new Point(_startPosX.Value + 100, _startPosY.Value), + new Point(_startPosX.Value + 145, _startPosY.Value + 20), + new Point(_startPosX.Value + 100, _startPosY.Value + 40), + new Point(_startPosX.Value, _startPosY.Value + 40), + new Point(_startPosX.Value, _startPosY.Value) }; // корпус @@ -196,34 +211,11 @@ g.DrawPolygon(pen, body); //боковина лодки - g.DrawEllipse(pen, _startPosX.Value + 25, _startPosY.Value + 30, 30, 30); - g.DrawEllipse(pen, _startPosX.Value + 70, _startPosY.Value + 30, 30, 30); - g.DrawLine(pen, _startPosX.Value + 37, _startPosY.Value + 30, _startPosX.Value + 83, _startPosY.Value + 30); - g.DrawLine(pen, _startPosX.Value + 37, _startPosY.Value + 60, _startPosX.Value + 83, _startPosY.Value + 60); - g.FillRectangle(brushBodyColor, _startPosX.Value + 37, _startPosY.Value + 31, 50, 29); - - - //защитное стекло спереди - if (EntityMotorBoat.ProtectiveGlass) - { - Point[] glass = - { - new Point(_startPosX.Value + 105, _startPosY.Value + 25), - new Point(_startPosX.Value + 100, _startPosY.Value), - new Point(_startPosX.Value + 90, _startPosY.Value), - new Point(_startPosX.Value + 90, _startPosY.Value + 25), - new Point(_startPosX.Value + 105, _startPosY.Value + 25) - }; - g.FillPolygon(brushAdditionalColor, glass); - g.DrawPolygon(pen, glass); - } - - //мотор - if (EntityMotorBoat.Engine) - { - g.FillRectangle(brushAdditionalColor, _startPosX.Value, _startPosY.Value + 50, 10, 25); - g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 50, 10, 25); - } + g.DrawEllipse(pen, _startPosX.Value + 15, _startPosY.Value + 5, 30, 30); + g.DrawEllipse(pen, _startPosX.Value + 60, _startPosY.Value + 5, 30, 30); + g.DrawLine(pen, _startPosX.Value + 27, _startPosY.Value + 5, _startPosX.Value + 73, _startPosY.Value + 5); + g.DrawLine(pen, _startPosX.Value + 27, _startPosY.Value + 35, _startPosX.Value + 73, _startPosY.Value + 35); + g.FillRectangle(brushBodyColor, _startPosX.Value + 27, _startPosY.Value + 6, 50, 29); } diff --git a/MotorBoat/MotorBoat/Drawnings/DrawningMotorBoat.cs b/MotorBoat/MotorBoat/Drawnings/DrawningMotorBoat.cs new file mode 100644 index 0000000..81d3781 --- /dev/null +++ b/MotorBoat/MotorBoat/Drawnings/DrawningMotorBoat.cs @@ -0,0 +1,65 @@ +using MotorBoat.Entities; + +namespace MotorBoat.Drawnings +{ + /// + /// Класс, отвечающий за прорисовку и перемещение объекта-сущности + /// + public class DrawningMotorBoat : DrawningBoat + { + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия защитного стекла + /// Признак наличия мотора + public DrawningMotorBoat(int speed, double weight, Color bodyColor, Color additionalColor, + bool protectiveGlass, bool engine) : base(153, 75) + { + EntityBoat = new EntityMotorBoat(speed, weight, bodyColor, additionalColor, protectiveGlass, engine); + } + /// + /// Прорисовка объекта + /// + /// + public override void DrawTransport(Graphics g) + { + if (EntityBoat == null || EntityBoat is not EntityMotorBoat motorBoat + || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + Pen pen = new(Color.Black); + Brush brushAdditionalColor = new SolidBrush(motorBoat.AdditionalColor); + + //защитное стекло спереди + if (motorBoat.ProtectiveGlass) + { + Point[] glass = + { + new Point(_startPosX.Value + 105, _startPosY.Value + 25), + new Point(_startPosX.Value + 100, _startPosY.Value), + new Point(_startPosX.Value + 90, _startPosY.Value), + new Point(_startPosX.Value + 90, _startPosY.Value + 25), + new Point(_startPosX.Value + 105, _startPosY.Value + 25) + }; + g.FillPolygon(brushAdditionalColor, glass); + g.DrawPolygon(pen, glass); + } + _startPosX += 10; + _startPosY += 25; + base.DrawTransport(g); + _startPosX -= 10; + _startPosY -= 25; + //мотор + if (motorBoat.Engine) + { + g.FillRectangle(brushAdditionalColor, _startPosX.Value, _startPosY.Value + 50, 10, 25); + g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 50, 10, 25); + } + } + } +} diff --git a/MotorBoat/MotorBoat/Entities/EntityBoat.cs b/MotorBoat/MotorBoat/Entities/EntityBoat.cs new file mode 100644 index 0000000..3390697 --- /dev/null +++ b/MotorBoat/MotorBoat/Entities/EntityBoat.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.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/MotorBoat/MotorBoat/EntityMotorBoat.cs b/MotorBoat/MotorBoat/Entities/EntityMotorBoat.cs similarity index 70% rename from MotorBoat/MotorBoat/EntityMotorBoat.cs rename to MotorBoat/MotorBoat/Entities/EntityMotorBoat.cs index 2757fdd..8d522e2 100644 --- a/MotorBoat/MotorBoat/EntityMotorBoat.cs +++ b/MotorBoat/MotorBoat/Entities/EntityMotorBoat.cs @@ -1,22 +1,10 @@ -namespace MotorBoat +namespace MotorBoat.Entities { /// /// Класс-сущность "Моторная лодка" /// - public class EntityMotorBoat + public class EntityMotorBoat : EntityBoat { - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } /// /// Дополнительный цвет (для опциональных элементов) /// @@ -42,12 +30,9 @@ /// Дополнительный цвет /// Признак наличия защитного стекла /// Признак наличия мотора - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, - bool protectiveGlass, bool engine) + public EntityMotorBoat(int speed, double weight, Color bodyColor, Color additionalColor, + bool protectiveGlass, bool engine) : base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; AdditionalColor = additionalColor; ProtectiveGlass = protectiveGlass; Engine = engine; diff --git a/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs b/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs index 5a6e469..ff05731 100644 --- a/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs +++ b/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs @@ -29,11 +29,12 @@ private void InitializeComponent() { pictureBoxMotorBoat = new PictureBox(); - buttonCreate = new Button(); + buttonCreateMotorBoat = new Button(); buttonLeft = new Button(); buttonDown = new Button(); buttonRight = new Button(); buttonUp = new Button(); + buttonCreateBoat = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxMotorBoat).BeginInit(); SuspendLayout(); // @@ -46,16 +47,16 @@ pictureBoxMotorBoat.TabIndex = 0; pictureBoxMotorBoat.TabStop = false; // - // buttonCreate + // buttonCreateMotorBoat // - buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(12, 412); - buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(75, 23); - buttonCreate.TabIndex = 1; - buttonCreate.Text = "Создать"; - buttonCreate.UseVisualStyleBackColor = true; - buttonCreate.Click += ButtonCreateMotorBoat_Click; + buttonCreateMotorBoat.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateMotorBoat.Location = new Point(12, 412); + buttonCreateMotorBoat.Name = "buttonCreateMotorBoat"; + buttonCreateMotorBoat.Size = new Size(174, 23); + buttonCreateMotorBoat.TabIndex = 1; + buttonCreateMotorBoat.Text = "Создать моторную лодку"; + buttonCreateMotorBoat.UseVisualStyleBackColor = true; + buttonCreateMotorBoat.Click += ButtonCreateMotorBoat_Click; // // buttonLeft // @@ -105,16 +106,28 @@ buttonUp.UseVisualStyleBackColor = true; buttonUp.Click += ButtonMove_Click; // + // buttonCreateBoat + // + buttonCreateBoat.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateBoat.Location = new Point(203, 412); + buttonCreateBoat.Name = "buttonCreateBoat"; + buttonCreateBoat.Size = new Size(174, 23); + buttonCreateBoat.TabIndex = 6; + buttonCreateBoat.Text = "Создать лодку"; + buttonCreateBoat.UseVisualStyleBackColor = true; + buttonCreateBoat.Click += ButtonCreateBoat_Click; + // // FormMotorBoat // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(861, 447); + Controls.Add(buttonCreateBoat); Controls.Add(buttonUp); Controls.Add(buttonRight); Controls.Add(buttonDown); Controls.Add(buttonLeft); - Controls.Add(buttonCreate); + Controls.Add(buttonCreateMotorBoat); Controls.Add(pictureBoxMotorBoat); Name = "FormMotorBoat"; Text = "Моторная лодка"; @@ -125,10 +138,11 @@ #endregion private PictureBox pictureBoxMotorBoat; - private Button buttonCreate; + private Button buttonCreateMotorBoat; private Button buttonLeft; private Button buttonDown; private Button buttonRight; private Button buttonUp; + private Button buttonCreateBoat; } } \ No newline at end of file diff --git a/MotorBoat/MotorBoat/FormMotorBoat.cs b/MotorBoat/MotorBoat/FormMotorBoat.cs index 8ff553a..8c83651 100644 --- a/MotorBoat/MotorBoat/FormMotorBoat.cs +++ b/MotorBoat/MotorBoat/FormMotorBoat.cs @@ -7,12 +7,13 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using MotorBoat.Drawnings; namespace MotorBoat { public partial class FormMotorBoat : Form { - private DrawningMotorBoat? _drawningMotorBoat; + private DrawningBoat? _drawningBoat; /// /// Конструктор формы /// @@ -25,36 +26,50 @@ namespace MotorBoat /// private void Draw() { - if (_drawningMotorBoat == null) + if (_drawningBoat == null) { return; } Bitmap bmp = new(pictureBoxMotorBoat.Width, pictureBoxMotorBoat.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningMotorBoat.DrawTransport(gr); + _drawningBoat.DrawTransport(gr); pictureBoxMotorBoat.Image = bmp; } + private void CreateObject(string type) + { + Random random = new Random(); + 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(DrawningMotorBoat): + _drawningBoat = new DrawningMotorBoat(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))); + break; + default: + return; + } + _drawningBoat.SetPictureSize(pictureBoxMotorBoat.Width, pictureBoxMotorBoat.Height); + _drawningBoat.SetPosition(random.Next(10, 100), random.Next(10, 100)); + Draw(); + } /// - /// Обработка нажатия кнопки "Создать" + /// Обработка нажатия кнопки "Создать моторную лодку" /// /// /// - private void ButtonCreateMotorBoat_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningMotorBoat = new DrawningMotorBoat(); - _drawningMotorBoat.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))); - _drawningMotorBoat.SetPictureSize(pictureBoxMotorBoat.Width, - pictureBoxMotorBoat.Height); - _drawningMotorBoat.SetPosition(random.Next(10, 100), random.Next(10, - 100)); - Draw(); - } + private void ButtonCreateMotorBoat_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningMotorBoat)); + /// + /// Обработка нажатия кнопки "Создать лодку" + /// + /// + /// + private void ButtonCreateBoat_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBoat)); /// /// Перемещение объекта по форме (нажатие кнопок навигации) /// @@ -62,7 +77,7 @@ namespace MotorBoat /// private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningMotorBoat == null) + if (_drawningBoat == null) { return; } @@ -72,19 +87,19 @@ namespace MotorBoat { case "buttonUp": result = - _drawningMotorBoat.MoveTransport(DirectionType.Up); + _drawningBoat.MoveTransport(DirectionType.Up); break; case "buttonDown": result = - _drawningMotorBoat.MoveTransport(DirectionType.Down); + _drawningBoat.MoveTransport(DirectionType.Down); break; case "buttonLeft": result = - _drawningMotorBoat.MoveTransport(DirectionType.Left); + _drawningBoat.MoveTransport(DirectionType.Left); break; case "buttonRight": result = - _drawningMotorBoat.MoveTransport(DirectionType.Right); + _drawningBoat.MoveTransport(DirectionType.Right); break; } if (result) -- 2.25.1 From d33425108d8d230135725c282ba12d8b8b5be7b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=B7=D0=B0=D0=BC=D0=B0=D1=82=20=D0=98=D1=88=D1=82?= =?UTF-8?q?=D1=83=D0=B3=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Mon, 11 Mar 2024 20:00:41 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=81=D1=82=D1=80=D0=B0=D1=82=D0=B5=D0=B3?= =?UTF-8?q?=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MotorBoat/Drawnings/DirectionType.cs | 4 + MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs | 16 +++ MotorBoat/MotorBoat/FormMotorBoat.Designer.cs | 26 ++++ MotorBoat/MotorBoat/FormMotorBoat.cs | 55 ++++++++ .../MovementStrategy/AbstractStrategy.cs | 119 ++++++++++++++++++ .../MovementStrategy/IMoveableObject.cs | 27 ++++ .../MovementStrategy/MoveToBorder.cs | 44 +++++++ .../MovementStrategy/MoveToCenter.cs | 57 +++++++++ .../MovementStrategy/MoveableBoat.cs | 59 +++++++++ .../MovementStrategy/MovementDirection.cs | 24 ++++ .../MovementStrategy/ObjectParameters.cs | 62 +++++++++ .../MovementStrategy/StrategyStatus.cs | 19 +++ 12 files changed, 512 insertions(+) create mode 100644 MotorBoat/MotorBoat/MovementStrategy/AbstractStrategy.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/IMoveableObject.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/MoveToBorder.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/MoveToCenter.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/MoveableBoat.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/MovementDirection.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/ObjectParameters.cs create mode 100644 MotorBoat/MotorBoat/MovementStrategy/StrategyStatus.cs diff --git a/MotorBoat/MotorBoat/Drawnings/DirectionType.cs b/MotorBoat/MotorBoat/Drawnings/DirectionType.cs index 7a584f2..30bcde3 100644 --- a/MotorBoat/MotorBoat/Drawnings/DirectionType.cs +++ b/MotorBoat/MotorBoat/Drawnings/DirectionType.cs @@ -6,6 +6,10 @@ /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, /// /// Вверх /// diff --git a/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs b/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs index f25e29b..ec1a9a8 100644 --- a/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs +++ b/MotorBoat/MotorBoat/Drawnings/DrawningBoat.cs @@ -38,6 +38,22 @@ namespace MotorBoat.Drawnings /// private readonly int _drawningBoatHeight = 38; /// + /// Координата Х объекта + /// + public int? GetPosX => _startPosX; + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _drawningBoatWidth; + /// + /// Высота объекта + /// + public int GetHeight => _drawningBoatHeight; + /// /// Пустой конструктор /// private DrawningBoat() diff --git a/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs b/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs index ff05731..961978e 100644 --- a/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs +++ b/MotorBoat/MotorBoat/FormMotorBoat.Designer.cs @@ -35,6 +35,8 @@ buttonRight = new Button(); buttonUp = new Button(); buttonCreateBoat = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxMotorBoat).BeginInit(); SuspendLayout(); // @@ -117,11 +119,33 @@ buttonCreateBoat.UseVisualStyleBackColor = true; buttonCreateBoat.Click += ButtonCreateBoat_Click; // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(724, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(774, 41); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(75, 23); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += buttonStrategyStep_Click; + // // FormMotorBoat // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(861, 447); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); Controls.Add(buttonCreateBoat); Controls.Add(buttonUp); Controls.Add(buttonRight); @@ -144,5 +168,7 @@ private Button buttonRight; private Button buttonUp; private Button buttonCreateBoat; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/MotorBoat/MotorBoat/FormMotorBoat.cs b/MotorBoat/MotorBoat/FormMotorBoat.cs index 8c83651..8cf446e 100644 --- a/MotorBoat/MotorBoat/FormMotorBoat.cs +++ b/MotorBoat/MotorBoat/FormMotorBoat.cs @@ -8,18 +8,30 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MotorBoat.Drawnings; +using MotorBoat.MovementStrategy; namespace MotorBoat { + /// + /// Форма работы с объектом "Моторная лодка" + /// public partial class FormMotorBoat : Form { + /// + /// Поле для прорисовки объекта + /// private DrawningBoat? _drawningBoat; /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + /// /// Конструктор формы /// public FormMotorBoat() { InitializeComponent(); + _strategy = null; } /// /// Метод прорисовки катера @@ -56,6 +68,8 @@ namespace MotorBoat } _drawningBoat.SetPictureSize(pictureBoxMotorBoat.Width, pictureBoxMotorBoat.Height); _drawningBoat.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; Draw(); } /// @@ -107,5 +121,46 @@ namespace MotorBoat Draw(); } } + + /// + /// + /// + /// + /// + 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 MoveableBoat(_drawningBoat), + pictureBoxMotorBoat.Width, pictureBoxMotorBoat.Height); + } + if (_strategy == null) + { + return; + } + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } + } } diff --git a/MotorBoat/MotorBoat/MovementStrategy/AbstractStrategy.cs b/MotorBoat/MotorBoat/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..934d404 --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,119 @@ +namespace MotorBoat.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; + } +} \ No newline at end of file diff --git a/MotorBoat/MotorBoat/MovementStrategy/IMoveableObject.cs b/MotorBoat/MotorBoat/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..f16a3c5 --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.MovementStrategy; +/// +/// Интерфейс для работы с перемещаемым объектом +/// +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/MotorBoat/MotorBoat/MovementStrategy/MoveToBorder.cs b/MotorBoat/MotorBoat/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..c59364e --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.MovementStrategy; +/// +/// Стратегия перемещения объекта к краю экрана +/// +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.RightBorder + GetStep() >= FieldWidth && + 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()) + { + MoveRight(); + } + + int diffY = objParams.DownBorder - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + MoveDown(); + } + } +} diff --git a/MotorBoat/MotorBoat/MovementStrategy/MoveToCenter.cs b/MotorBoat/MotorBoat/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..5f02253 --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorBoat.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(); + } + } + } +} \ No newline at end of file diff --git a/MotorBoat/MotorBoat/MovementStrategy/MoveableBoat.cs b/MotorBoat/MotorBoat/MovementStrategy/MoveableBoat.cs new file mode 100644 index 0000000..3bddf7c --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/MoveableBoat.cs @@ -0,0 +1,59 @@ +using MotorBoat.Drawnings; + +namespace MotorBoat.MovementStrategy; +/// +/// Класс-реализация IMoveableObject с использованием DrawningBoat +/// +public class MoveableBoat : IMoveableObject +{ + /// + /// Поле-объект класса DrawningBoat или его наследника + /// + private readonly DrawningBoat? _boat = null; + /// + /// Конструктор + /// + /// Объект класса DrawningBoat + public MoveableBoat(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/MotorBoat/MotorBoat/MovementStrategy/MovementDirection.cs b/MotorBoat/MotorBoat/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..315da02 --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/MovementDirection.cs @@ -0,0 +1,24 @@ +namespace MotorBoat.MovementStrategy; + +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 +} diff --git a/MotorBoat/MotorBoat/MovementStrategy/ObjectParameters.cs b/MotorBoat/MotorBoat/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..be6318d --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,62 @@ +namespace MotorBoat.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; + } +} \ No newline at end of file diff --git a/MotorBoat/MotorBoat/MovementStrategy/StrategyStatus.cs b/MotorBoat/MotorBoat/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..26d73b8 --- /dev/null +++ b/MotorBoat/MotorBoat/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,19 @@ +namespace MotorBoat.MovementStrategy; +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + /// + /// Выполняется + /// + InProgress, + /// + /// Завершено + /// + Finish +} -- 2.25.1