diff --git a/ProjectCatamaran/ProjectCatamaran/DrawningCatamaran.cs b/ProjectCatamaran/ProjectCatamaran/DrawningCatamaran.cs deleted file mode 100644 index 1762aa1..0000000 --- a/ProjectCatamaran/ProjectCatamaran/DrawningCatamaran.cs +++ /dev/null @@ -1,180 +0,0 @@ -using ProjectCatamaran; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -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 = 65; - /// - /// Высота прорисовки катамарана - /// - private readonly int _drawningCatamaranHeight = 40; - /// - /// Инициализация полей обьекта-класса спортивного автомобиля - /// - /// Скорость - /// Вес катера - /// Основной цвет - /// Дополнительный цвет(для опциональных элементов) - /// Признак (опция) наличие плавников - /// Признак (опция) наличие парус - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool floats, bool sail) - { - EntityCatamaran = new EntityCatamaran(); - EntityCatamaran.Init(speed, weight, bodyColor, additionalColor, floats, sail); - - _pictureWidth = null; - _pictureHeight = null; - _startPosX = null; - _startPosY = null; - } - /// - /// установка границ поля - /// - /// ширина - /// высота - /// - public bool SetPictureSize(int width, int height) - { - if (_drawningCatamaranHeight < height && _drawningCatamaranWidth < width) - { - _pictureHeight = height; - _pictureWidth = width; - return true; - } - return false; - } - /// - /// установка позиции - /// - /// координата x - /// координата y - public void SetPosition(int x, int y) - { - if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) - { - return; - } - if (x > _pictureWidth - _drawningCatamaranWidth || x < 0) - _startPosX = x < 0 ? 0 : _pictureWidth - _drawningCatamaranWidth; - else - _startPosX = x; - if (y > _pictureHeight - _drawningCatamaranHeight || y < 0) - _startPosY = y < 0 ? 0 : _pictureHeight - _drawningCatamaranHeight; - else - _startPosY = y; - } - /// - /// изменение направления перемещения - /// - /// направление - /// true - перемещение выполнено , 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 + (int)EntityCatamaran.Step + _drawningCatamaranWidth <= _pictureWidth) - { - _startPosX += (int)EntityCatamaran.Step; - } - return true; - case DirectionType.Down: - if (_startPosY.Value + (int)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; - } - Brush brBody = new SolidBrush(EntityCatamaran.BodyColor); - Brush brFloatsAndSail = new SolidBrush(EntityCatamaran.AdditionalColor); - g.FillRectangle(brBody, _startPosX.Value + 5, _startPosY.Value + 15, 40, 20); - Point[] triangle = - { - new Point(_startPosX.Value + 45,_startPosY.Value + 15), - new Point(_startPosX.Value + 65,_startPosY.Value + 25), - new Point(_startPosX.Value + 45,_startPosY.Value + 35), - }; - g.FillPolygon(brBody, triangle); - g.FillEllipse(new SolidBrush(Color.Black), _startPosX.Value + 12, _startPosY.Value + 19, 23, 10); - //плавники - if (EntityCatamaran.Floats) - { - g.FillRectangle(brFloatsAndSail, _startPosX.Value, _startPosY.Value + 10, 45, 5); - g.FillRectangle(brFloatsAndSail, _startPosX.Value, _startPosY.Value + 35, 45, 5); - } - // парус - if (EntityCatamaran.Sail) - { - Point[] sailFigure = - { - new Point(_startPosX.Value + 25,_startPosY.Value + 25), - new Point(_startPosX.Value + 35 ,_startPosY.Value + 25), - new Point(_startPosX.Value + 25,_startPosY.Value), - }; - g.FillPolygon(brFloatsAndSail, sailFigure); - } - } - - - -} \ No newline at end of file diff --git a/ProjectCatamaran/ProjectCatamaran/Drawnings/DirectionType.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/DirectionType.cs new file mode 100644 index 0000000..15c6362 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/DirectionType.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Drawnings; + +public enum DirectionType +{ + /// + /// неизвестное направление + /// + Unknown = -1, + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 +} \ No newline at end of file diff --git a/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoat.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoat.cs new file mode 100644 index 0000000..34b2b2c --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningBoat.cs @@ -0,0 +1,192 @@ +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 = 60; + /// + /// Высота прорисовки лодки + /// + private readonly int _drawningBoatHeight = 22; + /// + /// координата х обьекта + /// + 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; + } + /// + /// Конструктор + /// + /// Скорость + /// Вес катера + /// Основной цвет + public DrawningBoat(int speed, double weight, Color bodyColor) : this() + { + EntityBoat = new EntityBoat(speed, weight, bodyColor); + + } + /// + /// Конструктор + /// + /// Ширина катера + /// высота катера + public DrawningBoat(int drawningBoatWidth, int drawningBoatHeight) : this() + { + _drawningBoatWidth = drawningBoatWidth; + _drawningBoatHeight = drawningBoatHeight; + + } + /// + /// установка границ поля + /// + /// ширина + /// высота + /// + public bool SetPictureSize(int width, int height) + { + if (_drawningBoatHeight < height && _drawningBoatWidth < width) + { + _pictureHeight = height; + _pictureWidth = width; + return true; + } + return false; + } + /// + /// установка позиции + /// + /// координата x + /// координата y + public void SetPosition(int x, int y) + { + if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) + { + return; + } + if (x > _pictureWidth - _drawningBoatWidth || x < 0) + _startPosX = x < 0 ? 0 : _pictureWidth - _drawningBoatWidth; + else + _startPosX = x; + if (y > _pictureHeight - _drawningBoatHeight || y < 0) + _startPosY = y < 0 ? 0 : _pictureHeight - _drawningBoatHeight; + else + _startPosY = y; + } + /// + /// изменение направления перемещения + /// + /// направление + /// true - перемещение выполнено , 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 + (int)EntityBoat.Step + _drawningBoatWidth <= _pictureWidth) + { + _startPosX += (int)EntityBoat.Step; + } + return true; + case DirectionType.Down: + if (_startPosY.Value + (int)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; + } + Brush brBody = new SolidBrush(EntityBoat.BodyColor); + + g.FillRectangle(brBody, _startPosX.Value, _startPosY.Value, 40, 20); + Point[] triangle = + { + new Point(_startPosX.Value + 40,_startPosY.Value), + new Point(_startPosX.Value + 60,_startPosY.Value + 10), + new Point(_startPosX.Value + 40,_startPosY.Value + 20), + }; + g.FillPolygon(brBody, triangle); + g.FillEllipse(new SolidBrush(Color.Black), _startPosX.Value + 7, _startPosY.Value + 4, 23, 10); + + } + + +} + diff --git a/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningCatamaran.cs b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningCatamaran.cs new file mode 100644 index 0000000..523ff6e --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Drawnings/DrawningCatamaran.cs @@ -0,0 +1,60 @@ +using ProjectCatamaran.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.Drawnings; +/// +/// класс отвечающиай за перемещение и отрисовку +/// +public class DrawningCatamaran : DrawningBoat +{ + /// + /// Конструктор + /// + /// Скорость + /// Вес катера + /// Основной цвет + /// Дополнительный цвет(для опциональных элементов) + /// Признак (опция) наличие плавников + /// Признак (опция) наличие парус + public DrawningCatamaran(int speed, double weight, Color bodyColor, Color additionalColor, bool floats, bool sail) : + base(65,40) + { + EntityBoat = new EntityCatamaran(speed, weight, bodyColor, additionalColor, floats, sail); + } + + public override void DrawTransport(Graphics g) + { + if (EntityBoat == null || EntityBoat is not EntityCatamaran catamaran || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + _startPosX += 5; + _startPosY += 15; + base.DrawTransport(g); + _startPosX -= 5; + _startPosY -= 15; + Brush brFloatsAndSail = new SolidBrush(catamaran.AdditionalColor); + //плавники + if (catamaran.Floats) + { + g.FillRectangle(brFloatsAndSail, _startPosX.Value, _startPosY.Value + 10, 45, 5); + g.FillRectangle(brFloatsAndSail, _startPosX.Value, _startPosY.Value + 35, 45, 5); + } + // парус + if (catamaran.Sail) + { + Point[] sailFigure = + { + new Point(_startPosX.Value + 25,_startPosY.Value + 25), + new Point(_startPosX.Value + 35 ,_startPosY.Value + 25), + new Point(_startPosX.Value + 25,_startPosY.Value), + }; + g.FillPolygon(brFloatsAndSail, sailFigure); + } + } +} \ No newline at end of file diff --git a/ProjectCatamaran/ProjectCatamaran/Entities/EntityBoat.cs b/ProjectCatamaran/ProjectCatamaran/Entities/EntityBoat.cs new file mode 100644 index 0000000..442dbc3 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Entities/EntityBoat.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +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 63% rename from ProjectCatamaran/ProjectCatamaran/EntityCatamaran.cs rename to ProjectCatamaran/ProjectCatamaran/Entities/EntityCatamaran.cs index 61d027e..b2cb8e6 100644 --- a/ProjectCatamaran/ProjectCatamaran/EntityCatamaran.cs +++ b/ProjectCatamaran/ProjectCatamaran/Entities/EntityCatamaran.cs @@ -1,21 +1,9 @@ -namespace ProjectCatamaran; +namespace ProjectCatamaran.Entities; /// -/// Класс-сущность "Катамаран" +/// Класс-сущность "Катамарана" /// -public class EntityCatamaran +public class EntityCatamaran : EntityBoat { - /// - /// Скорость - /// - public int Speed { get; set; } - /// - /// Вес авто - /// - public double Weight { get; set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } /// /// Дополнительный цвет(для опциональных элементов) /// @@ -29,10 +17,6 @@ public class EntityCatamaran /// public bool Sail { get; private set; } /// - /// Шаг перемещения - /// - public double Step => Speed * 100 / Weight; - /// /// Инициализация полей обьекта-класса спортивного автомобиля /// /// Скорость @@ -41,11 +25,9 @@ public class EntityCatamaran /// Дополнительный цвет(для опциональных элементов) /// Признак (опция) наличие плавников /// Признак (опция) наличие паруса - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool floats, bool sail) + public EntityCatamaran(int speed, double weight, Color bodyColor, Color additionalColor, bool floats, bool sail) + : base(speed,weight,bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; AdditionalColor = additionalColor; Floats = floats; Sail = sail; diff --git a/ProjectCatamaran/ProjectCatamaran/FormCatamaran.Designer.cs b/ProjectCatamaran/ProjectCatamaran/FormCatamaran.Designer.cs index 12e51bf..5c03681 100644 --- a/ProjectCatamaran/ProjectCatamaran/FormCatamaran.Designer.cs +++ b/ProjectCatamaran/ProjectCatamaran/FormCatamaran.Designer.cs @@ -34,6 +34,9 @@ buttonRight = new Button(); buttonLeft = new Button(); buttonDown = new Button(); + buttonCreateBoat = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxCatamaran).BeginInit(); SuspendLayout(); // @@ -42,18 +45,18 @@ pictureBoxCatamaran.Dock = DockStyle.Fill; pictureBoxCatamaran.Location = new Point(0, 0); pictureBoxCatamaran.Name = "pictureBoxCatamaran"; - pictureBoxCatamaran.Size = new Size(800, 450); + pictureBoxCatamaran.Size = new Size(801, 450); pictureBoxCatamaran.TabIndex = 0; pictureBoxCatamaran.TabStop = false; // // buttonCreateCatamaran // buttonCreateCatamaran.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; - buttonCreateCatamaran.Location = new Point(12, 406); + buttonCreateCatamaran.Location = new Point(12, 402); buttonCreateCatamaran.Name = "buttonCreateCatamaran"; - buttonCreateCatamaran.Size = new Size(75, 23); + buttonCreateCatamaran.Size = new Size(166, 40); buttonCreateCatamaran.TabIndex = 1; - buttonCreateCatamaran.Text = "Создать"; + buttonCreateCatamaran.Text = "Создать катамаран"; buttonCreateCatamaran.UseVisualStyleBackColor = true; buttonCreateCatamaran.Click += ButtonCreateCatamaran_Click; // @@ -105,11 +108,46 @@ buttonDown.UseVisualStyleBackColor = true; buttonDown.Click += ButtonMove_Click; // + // buttonCreateBoat + // + buttonCreateBoat.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonCreateBoat.Location = new Point(184, 402); + buttonCreateBoat.Name = "buttonCreateBoat"; + buttonCreateBoat.Size = new Size(166, 40); + buttonCreateBoat.TabIndex = 6; + buttonCreateBoat.Text = "Создать лодку"; + buttonCreateBoat.UseVisualStyleBackColor = true; + buttonCreateBoat.Click += ButtonCreateBoat_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(668, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(709, 41); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.RightToLeft = RightToLeft.Yes; + buttonStrategyStep.Size = new Size(75, 23); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormCatamaran // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(800, 450); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreateBoat); Controls.Add(buttonDown); Controls.Add(buttonLeft); Controls.Add(buttonRight); @@ -130,5 +168,8 @@ private Button buttonRight; private Button buttonLeft; private Button buttonDown; + private Button buttonCreateBoat; + 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 1560145..e008569 100644 --- a/ProjectCatamaran/ProjectCatamaran/FormCatamaran.cs +++ b/ProjectCatamaran/ProjectCatamaran/FormCatamaran.cs @@ -1,39 +1,43 @@ -using ProjectCatamaran; +using ProjectCatamaran.Drawnings; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; +using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using ProjectCatamaran.MovementStrategy; namespace ProjectCatamaran { public partial class FormCatamaran : Form { - private DrawningCatamaran? _drawningCatamaran; + private DrawningBoat? _drawningBoat; + private AbstractStrategy? _strategy; public FormCatamaran() { InitializeComponent(); + _strategy = null; } 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; } - + private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningCatamaran == null) + if (_drawningBoat == null) { return; } @@ -42,16 +46,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) @@ -60,18 +64,77 @@ namespace ProjectCatamaran } } + 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))); + 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 Random(); - _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))); + CreateObject(nameof(DrawningCatamaran)); + } - _drawningCatamaran.SetPictureSize(pictureBoxCatamaran.Width, pictureBoxCatamaran.Height); - _drawningCatamaran.SetPosition(random.Next(10, 100), random.Next(10, 100)); + private void ButtonCreateBoat_Click(object sender, EventArgs e) + { + CreateObject(nameof(DrawningBoat)); + } + /// + /// Обработка нажатия кнопки "Шаг" + /// + /// + /// + 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), + pictureBoxCatamaran.Width, pictureBoxCatamaran.Height); + } + if (_strategy == null) + { + return; + } + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); Draw(); + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } } } } \ No newline at end of file diff --git a/ProjectCatamaran/ProjectCatamaran/MovementStrategy/AbstractStrategy.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..d2395be --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,124 @@ +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 (IsTargetDestination()) + { + _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 IsTargetDestination(); + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат попытки (true - удалось переместиться, false - неудача) + private bool MoveTo(MovementDirection movementDirection) + { + if (_state != StrategyStatus.InProgress) + { + return false; + } + return _moveableObject?.TryMoveObject(movementDirection) ?? false; + } +} + diff --git a/ProjectCatamaran/ProjectCatamaran/MovementStrategy/IMoveableObjects.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/IMoveableObjects.cs new file mode 100644 index 0000000..49cfdbe --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/IMoveableObjects.cs @@ -0,0 +1,25 @@ +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..da1d690 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,37 @@ +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 void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + return; + if (objParams.RightBorder + GetStep() <= FieldWidth) + MoveRight(); + if (objParams.DownBorder + GetStep() <= FieldHeight) + MoveDown(); + + } + /// + /// проверка достижения цели + /// + /// true - достиг , false - нет + protected override bool IsTargetDestination() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + return false; + return objParams.RightBorder + GetStep() > FieldWidth && + objParams.DownBorder + GetStep() > FieldHeight ; + } +} + diff --git a/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveToCenter.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..280f6f3 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,60 @@ +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 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(); + } + } + } + + protected override bool IsTargetDestination() + { + 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; + } + +} + diff --git a/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveableBoat.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveableBoat.cs new file mode 100644 index 0000000..bf63e73 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MoveableBoat.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectCatamaran.Drawnings; + +namespace ProjectCatamaran.MovementStrategy +{ + internal 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 + /// + /// + /// 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.Unknown + }; + } + } +} diff --git a/ProjectCatamaran/ProjectCatamaran/DirectionType.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MovementDirection.cs similarity index 79% rename from ProjectCatamaran/ProjectCatamaran/DirectionType.cs rename to ProjectCatamaran/ProjectCatamaran/MovementStrategy/MovementDirection.cs index 18ae55c..0c99da6 100644 --- a/ProjectCatamaran/ProjectCatamaran/DirectionType.cs +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/MovementDirection.cs @@ -4,11 +4,11 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ProjectCatamaran; - -public enum DirectionType +namespace ProjectCatamaran.MovementStrategy; +public enum MovementDirection { - /// + + /// /// Вверх /// Up = 1, @@ -24,4 +24,4 @@ public enum DirectionType /// Вправо /// Right = 4 -} \ No newline at end of file +} diff --git a/ProjectCatamaran/ProjectCatamaran/MovementStrategy/ObjectParameters.cs b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..b9d9e0b --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,66 @@ +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..fe0389a --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,13 @@ +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 +}