diff --git a/AntiAircraftGun/DirectionAntiAircraftGun.cs b/AntiAircraftGun/Drawnings/DirectionAntiAircraftGun.cs similarity index 72% rename from AntiAircraftGun/DirectionAntiAircraftGun.cs rename to AntiAircraftGun/Drawnings/DirectionAntiAircraftGun.cs index 05de63e..476fd00 100644 --- a/AntiAircraftGun/DirectionAntiAircraftGun.cs +++ b/AntiAircraftGun/Drawnings/DirectionAntiAircraftGun.cs @@ -1,10 +1,12 @@ - -namespace AntiAircraftGun; +namespace AntiAircraftGun.Drawnings; /// /// Направление перемещения /// public enum DirectionType -{ +{ /// + /// Неизвестное направление + /// + Unknow = -1, /// /// Вверх /// diff --git a/AntiAircraftGun/DrawningAntiAircraftGun.cs b/AntiAircraftGun/Drawnings/DrawningAircraftGun.cs similarity index 60% rename from AntiAircraftGun/DrawningAntiAircraftGun.cs rename to AntiAircraftGun/Drawnings/DrawningAircraftGun.cs index 4652200..097115b 100644 --- a/AntiAircraftGun/DrawningAntiAircraftGun.cs +++ b/AntiAircraftGun/Drawnings/DrawningAircraftGun.cs @@ -1,56 +1,96 @@ -namespace AntiAircraftGun; -/// -/// Класс отвечающий за прорисовку и перемещение объекта - сущности -/// -public class DrawningAntiAircraftGun +using AntiAircraftGun.Entities; + +namespace AntiAircraftGun.Drawnings; + +public class DrawningAircraftGun { /// - /// Класс - сущность + /// Класс-сущность /// - public EntityAntiAircraftGun? EntityAntiAircraftGun { get; set; } + public EntityAircraftGun? EntityAircraftGun { get; protected set; } + /// - /// Ширина окна + /// Ширина /// private int? _pictureWidth; + /// - /// Высота окна + /// Высота /// private int? _pictureHeight; + /// /// Левая координата прорисовки зенитной установки /// - private int? _startPosX; + protected int? _startPosX; + /// /// Верхняя координата прорисовки зенитной установки /// - private int? _startPosY; + protected int? _startPosY; + /// /// Ширина прорисовки зенитной установки /// - private readonly int _drawningGunWidth = 130; + private readonly int _drawningGunWidth = 129; + /// /// Высота прорисовки зенитной установки /// - private readonly int _drawningGunHeight = 100; + private readonly int _drawningGunHeight = 105; + /// - /// Инициализация полей объекта-класса зенитной установки + /// Координата Х объекта /// - /// Скорость - /// Вес - /// Основной цвет - /// Дополнительный цвет - /// Наличие обвеса - /// Наличие башни - /// Наличие радара - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyKit, bool tower, bool radar) + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningGunWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawningGunHeight; + + /// + /// Пустой конструктор + /// + private DrawningAircraftGun() { - EntityAntiAircraftGun = new EntityAntiAircraftGun(); - EntityAntiAircraftGun.Init(speed, weight, bodyColor, additionalColor, bodyKit, tower, radar); _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + public DrawningAircraftGun(int speed, double weight, Color bodyColor) : this() + { + EntityAircraftGun = new EntityAircraftGun(speed, weight, bodyColor); + } + + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки зенитной установки + /// Высота прорисовки зенитной установки + protected DrawningAircraftGun(int drawningGunWidth, int drawningGunHeight) : this() + { + _drawningGunWidth = drawningGunWidth; + _drawningGunHeight = drawningGunHeight; + } /// /// Установка границ поля /// @@ -59,8 +99,7 @@ public class DrawningAntiAircraftGun /// public bool SetPictureSize(int width, int height) { - // TODO проверка, что объект "влезает" в размеры поля - // если влезает, сохраняем границы и корректируем позицию объекта,если она была уже установлена + if (width < _drawningGunWidth || height < _drawningGunHeight) { return false; }; _pictureWidth = width; _pictureHeight = height; @@ -93,8 +132,7 @@ public class DrawningAntiAircraftGun public void SetPosition(int x, int y) { - // TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы - // то надо изменить координаты, чтобы он оставался в этих границах + if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) { return; @@ -133,34 +171,34 @@ public class DrawningAntiAircraftGun /// public bool MoveTransport(DirectionType direction) { - if (EntityAntiAircraftGun == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityAircraftGun == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; } switch (direction) { case DirectionType.Left: - if (_startPosX.Value - EntityAntiAircraftGun.Step > 0) + if (_startPosX.Value - EntityAircraftGun.Step > 0) { - _startPosX -= (int)EntityAntiAircraftGun.Step; + _startPosX -= (int)EntityAircraftGun.Step; } return true; case DirectionType.Right: - if (_startPosX.Value + _drawningGunWidth + EntityAntiAircraftGun.Step < _pictureWidth) + if (_startPosX.Value + _drawningGunWidth + EntityAircraftGun.Step < _pictureWidth) { - _startPosX += (int)EntityAntiAircraftGun.Step; + _startPosX += (int)EntityAircraftGun.Step; } return true; case DirectionType.Down: - if (_startPosY.Value + _drawningGunHeight + EntityAntiAircraftGun.Step < _pictureHeight) + if (_startPosY.Value + _drawningGunHeight + EntityAircraftGun.Step < _pictureHeight) { - _startPosY += (int)EntityAntiAircraftGun.Step; + _startPosY += (int)EntityAircraftGun.Step; } return true; - case DirectionType.Up: //вверх - if (_startPosY - EntityAntiAircraftGun.Step > 0) + case DirectionType.Up: + if (_startPosY - EntityAircraftGun.Step > 0) { - _startPosY -= (int)EntityAntiAircraftGun.Step; + _startPosY -= (int)EntityAircraftGun.Step; } return true; default: @@ -171,22 +209,21 @@ public class DrawningAntiAircraftGun /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { - if (EntityAntiAircraftGun == null || !_startPosX.HasValue || !_startPosY.HasValue) + if (EntityAircraftGun == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } Pen pen = new(Color.Black); - Brush additionalBrush = new SolidBrush(EntityAntiAircraftGun.AdditionalColor); g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 75, 30, 30); g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 75, 30, 30); g.DrawRectangle(pen, _startPosX.Value + 25, _startPosY.Value + 75, 90, 30); //границы ЦВЕТ - Brush brDarkSlateGray = new SolidBrush(EntityAntiAircraftGun.BodyColor); + Brush brDarkSlateGray = new SolidBrush(EntityAircraftGun.BodyColor); g.FillRectangle(brDarkSlateGray, _startPosX.Value + 35, _startPosY.Value + 40, 35, 30); g.FillEllipse(brDarkSlateGray, _startPosX.Value + 10, _startPosY.Value + 75, 30, 30); g.FillEllipse(brDarkSlateGray, _startPosX.Value + 100, _startPosY.Value + 75, 30, 30); @@ -219,27 +256,8 @@ public class DrawningAntiAircraftGun g.DrawEllipse(pen, _startPosX.Value + 103, _startPosY.Value + 78, 24, 24); g.FillRectangle(brDarkSlateGray, _startPosX.Value + 10, _startPosY.Value + 65, 120, 13); + - if (EntityAntiAircraftGun.Tower) - { - g.FillRectangle(additionalBrush, _startPosX.Value + 35, _startPosY.Value + 50, 35, 15); - g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 50, 35, 15); - g.DrawLine(pen, _startPosX.Value + 45, _startPosY.Value + 50, _startPosX.Value + 90, _startPosY.Value + 20); - g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value + 50, _startPosX.Value + 95, _startPosY.Value + 27); - g.DrawLine(pen, _startPosX.Value + 45, _startPosY.Value + 50, _startPosX.Value + 60, _startPosY.Value + 50); - g.DrawLine(pen, _startPosX.Value + 90, _startPosY.Value + 20, _startPosX.Value + 95, _startPosY.Value + 27); - g.DrawLine(pen, _startPosX.Value + 90, _startPosY.Value + 20, _startPosX.Value + 100, _startPosY.Value + 20); - g.DrawLine(pen, _startPosX.Value + 100, _startPosY.Value + 20, _startPosX.Value + 95, _startPosY.Value + 27); - - } - - if (EntityAntiAircraftGun.Radar) - { - g.DrawLine(pen, _startPosX.Value + 20, _startPosY.Value + 65, _startPosX.Value + 20, _startPosY.Value + 40); - g.FillRectangle(additionalBrush, _startPosX.Value + 10, _startPosY.Value + 40, 20, 20); - g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 40, 20, 20); - } - - + } -} \ No newline at end of file +} diff --git a/AntiAircraftGun/Drawnings/DrawningAntiAircraftGun.cs b/AntiAircraftGun/Drawnings/DrawningAntiAircraftGun.cs new file mode 100644 index 0000000..ffe3fd0 --- /dev/null +++ b/AntiAircraftGun/Drawnings/DrawningAntiAircraftGun.cs @@ -0,0 +1,63 @@ +using AntiAircraftGun.Entities; + +namespace AntiAircraftGun.Drawnings; +/// +/// Класс отвечающий за прорисовку и перемещение объекта - сущности +/// +public class DrawningAntiAircraftGun : DrawningAircraftGun +{ + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия башни + /// Признак наличия радара + + public DrawningAntiAircraftGun(int speed, double weight, Color bodyColor, Color additionalColor, bool radar, bool tower) : base(129, 105) + { + EntityAircraftGun = new EntityAntiAircraftGun(speed, weight, bodyColor, radar, tower, additionalColor); + } + /// + /// Прорисовка объекта + /// + /// + public override void DrawTransport(Graphics g) + { + if (EntityAircraftGun == null || EntityAircraftGun is not EntityAntiAircraftGun aircraftGun || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + + Pen pen = new(Color.Black); + Brush additionalBrush = new SolidBrush(aircraftGun.AdditionalColor); + + base.DrawTransport(g); + + + if (aircraftGun.Tower) + { + g.FillRectangle(additionalBrush, _startPosX.Value + 35, _startPosY.Value + 50, 35, 15); + g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 50, 35, 15); + g.DrawLine(pen, _startPosX.Value + 45, _startPosY.Value + 50, _startPosX.Value + 90, _startPosY.Value + 20); + g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value + 50, _startPosX.Value + 95, _startPosY.Value + 27); + g.DrawLine(pen, _startPosX.Value + 45, _startPosY.Value + 50, _startPosX.Value + 60, _startPosY.Value + 50); + g.DrawLine(pen, _startPosX.Value + 90, _startPosY.Value + 20, _startPosX.Value + 95, _startPosY.Value + 27); + g.DrawLine(pen, _startPosX.Value + 90, _startPosY.Value + 20, _startPosX.Value + 100, _startPosY.Value + 20); + g.DrawLine(pen, _startPosX.Value + 100, _startPosY.Value + 20, _startPosX.Value + 95, _startPosY.Value + 27); + + } + + if (aircraftGun.Radar) + { + g.DrawLine(pen, _startPosX.Value + 20, _startPosY.Value + 65, _startPosX.Value + 20, _startPosY.Value + 40); + g.FillRectangle(additionalBrush, _startPosX.Value + 10, _startPosY.Value + 40, 20, 20); + g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 40, 20, 20); + } + + + } +} \ No newline at end of file diff --git a/AntiAircraftGun/Entities/EntityAircraftGun.cs b/AntiAircraftGun/Entities/EntityAircraftGun.cs new file mode 100644 index 0000000..03e77b0 --- /dev/null +++ b/AntiAircraftGun/Entities/EntityAircraftGun.cs @@ -0,0 +1,36 @@ +namespace AntiAircraftGun.Entities; +/// +/// Класс - сущность Бронированная машина +/// +public class EntityAircraftGun +{ + /// + /// Скорость + /// + 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 EntityAircraftGun(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } +} diff --git a/AntiAircraftGun/EntityAntiAircraftGun.cs b/AntiAircraftGun/Entities/EntityAntiAircraftGun.cs similarity index 51% rename from AntiAircraftGun/EntityAntiAircraftGun.cs rename to AntiAircraftGun/Entities/EntityAntiAircraftGun.cs index 86d6c8e..404ba48 100644 --- a/AntiAircraftGun/EntityAntiAircraftGun.cs +++ b/AntiAircraftGun/Entities/EntityAntiAircraftGun.cs @@ -1,29 +1,14 @@ -namespace AntiAircraftGun; +namespace AntiAircraftGun.Entities; /// /// Класс-сущность Зенитная установка /// -public class EntityAntiAircraftGun -{ /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } +public class EntityAntiAircraftGun : EntityAircraftGun +{ /// /// Дополниетльный цвет /// public Color AdditionalColor { get; private set; } /// - /// Наличие обвеса - /// - public bool BodyKit { get; private set; } - /// /// Наличие башни /// public bool Tower { get; private set; } @@ -31,28 +16,20 @@ public class EntityAntiAircraftGun /// Наличие радара /// public bool Radar { get; private set; } + /// - /// Шаг перемещения гидросамолета - /// - public double Step => Speed * 100 / Weight; - /// - /// Инициализация полей объекта-класса гидросамолета + /// Инициализация полей объекта-класса зенитной установки /// /// Скорость /// Вес /// Основной цвет /// Дополнительный цвет - /// Наличие обвеса /// Наличие башни /// Наличие радара - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyKit, bool tower, bool radar) - { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; - AdditionalColor = additionalColor; - BodyKit = bodyKit; - Tower = tower; + public EntityAntiAircraftGun(int speed, double weight, Color bodyColor, bool radar, bool tower, Color additionalColor) : base(speed, weight, bodyColor) + { Radar = radar; + Tower = tower; + AdditionalColor = additionalColor; } } diff --git a/AntiAircraftGun/FormAntiAircraftGun.Designer.cs b/AntiAircraftGun/FormAntiAircraftGun.Designer.cs index 7d69786..5f13f5f 100644 --- a/AntiAircraftGun/FormAntiAircraftGun.Designer.cs +++ b/AntiAircraftGun/FormAntiAircraftGun.Designer.cs @@ -29,11 +29,14 @@ private void InitializeComponent() { pictureBoxAntiAircraftGun = new PictureBox(); - buttonCreate = new Button(); buttonLeft = new Button(); buttonDown = new Button(); buttonRight = new Button(); buttonUp = new Button(); + buttonCreate = new Button(); + buttonCreatAircraftGun = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxAntiAircraftGun).BeginInit(); SuspendLayout(); // @@ -46,17 +49,6 @@ pictureBoxAntiAircraftGun.TabIndex = 0; pictureBoxAntiAircraftGun.TabStop = false; // - // buttonCreate - // - buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(12, 406); - buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(95, 32); - buttonCreate.TabIndex = 1; - buttonCreate.Text = "Создать"; - buttonCreate.UseVisualStyleBackColor = true; - buttonCreate.Click += ButtonCreate_Click; - // // buttonLeft // buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; @@ -105,11 +97,56 @@ buttonUp.UseVisualStyleBackColor = true; buttonUp.Click += ButtonMove_Click; // + // buttonCreate + // + buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreate.Location = new Point(12, 406); + buttonCreate.Name = "buttonCreate"; + buttonCreate.Size = new Size(215, 32); + buttonCreate.TabIndex = 1; + buttonCreate.Text = "Создать зенитную установку"; + buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += ButtonCreate_Click; + // + // buttonCreatAircraftGun + // + buttonCreatAircraftGun.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreatAircraftGun.Location = new Point(233, 406); + buttonCreatAircraftGun.Name = "buttonCreatAircraftGun"; + buttonCreatAircraftGun.Size = new Size(215, 32); + buttonCreatAircraftGun.TabIndex = 6; + buttonCreatAircraftGun.Text = "Создать бронированную машину"; + buttonCreatAircraftGun.UseVisualStyleBackColor = true; + buttonCreatAircraftGun.Click += buttonCreatAircraftGun_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(667, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(713, 41); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(75, 23); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += buttonStrategyStep_Click; + // // FormAntiAircraftGun // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(800, 450); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreatAircraftGun); Controls.Add(buttonUp); Controls.Add(buttonRight); Controls.Add(buttonDown); @@ -125,10 +162,13 @@ #endregion private PictureBox pictureBoxAntiAircraftGun; - private Button buttonCreate; private Button buttonLeft; private Button buttonDown; private Button buttonRight; private Button buttonUp; + private Button buttonCreate; + private Button buttonCreatAircraftGun; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/AntiAircraftGun/FormAntiAircraftGun.cs b/AntiAircraftGun/FormAntiAircraftGun.cs index cca877f..db4b09f 100644 --- a/AntiAircraftGun/FormAntiAircraftGun.cs +++ b/AntiAircraftGun/FormAntiAircraftGun.cs @@ -1,81 +1,155 @@ -namespace AntiAircraftGun -{ - public partial class FormAntiAircraftGun : Form - { - /// - /// Поле объект для прорисовки объекта - /// - private DrawningAntiAircraftGun? _drawningAntiAircraftGun; - /// - /// конструктор формы - /// - public FormAntiAircraftGun() - { - InitializeComponent(); - } - /// - /// Метод прорисовки транспорта - /// - private void Draw() - { - if (_drawningAntiAircraftGun == null) - { - return; - } - Bitmap bmp = new(pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height); - Graphics gr = Graphics.FromImage(bmp); - _drawningAntiAircraftGun.DrawTransport(gr); - pictureBoxAntiAircraftGun.Image = bmp; - } - /// - /// Обработка кнопик Создать - /// - /// - /// - private void ButtonCreate_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningAntiAircraftGun = new DrawningAntiAircraftGun(); - _drawningAntiAircraftGun.Init(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 255), - random.Next(0, 255), random.Next(0, 255)), Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); - _drawningAntiAircraftGun.SetPictureSize(pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height); - _drawningAntiAircraftGun.SetPosition(random.Next(10, 100), random.Next(10, 100)); +using AntiAircraftGun.Drawnings; +using AntiAircraftGun.MovementStrategy; +namespace AntiAircraftGun; + +public partial class FormAntiAircraftGun : Form +{ + /// + /// Поле объект для прорисовки объекта + /// + private DrawningAircraftGun? _drawningAircraftGun; + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + /// + /// конструктор формы + /// + public FormAntiAircraftGun() + { + InitializeComponent(); + _strategy = null; + } + /// + /// Метод прорисовки транспорта + /// + private void Draw() + { + if (_drawningAircraftGun == null) + { + return; + } + Bitmap bmp = new(pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height); + Graphics gr = Graphics.FromImage(bmp); + _drawningAircraftGun.DrawTransport(gr); + pictureBoxAntiAircraftGun.Image = bmp; + } + /// + /// Метод создания объекта + /// + /// + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawningAircraftGun): + _drawningAircraftGun = new DrawningAircraftGun(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(DrawningAntiAircraftGun): + _drawningAircraftGun = new DrawningAntiAircraftGun(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; + } + + _drawningAircraftGun.SetPictureSize(pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height); + _drawningAircraftGun.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } + /// + /// Обработка кнопик Создать Зенитную установку + /// + /// + /// + private void ButtonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAntiAircraftGun)); + /// + /// Обработка кнопик Создать установку + /// + /// + /// + private void buttonCreatAircraftGun_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAircraftGun)); + + /// + /// Перемещение объекта по форме + /// + /// + /// + private void ButtonMove_Click(object sender, EventArgs e) + { + if (_drawningAircraftGun == null) + { + return; + } + string name = ((Button)sender)?.Name ?? string.Empty; + bool result = false; + switch (name) + { + case "buttonUp": + result = _drawningAircraftGun.MoveTransport(DirectionType.Up); + break; + case "buttonDown": + result = _drawningAircraftGun.MoveTransport(DirectionType.Down); + break; + case "buttonRight": + result = _drawningAircraftGun.MoveTransport(DirectionType.Right); + break; + case "buttonLeft": + result = _drawningAircraftGun.MoveTransport(DirectionType.Left); + break; + } + if (result) + { Draw(); } - /// - /// Перемещение объекта по форме - /// - /// - /// - private void ButtonMove_Click(object sender, EventArgs e) + } + /// + /// Метод выбора стратегии + /// + /// + /// + private void buttonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningAircraftGun == null) { - if (_drawningAntiAircraftGun == null) + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) { return; } - string name = ((Button)sender)?.Name ?? string.Empty; - bool result = false; - switch (name) - { - case "buttonUp": - result = _drawningAntiAircraftGun.MoveTransport(DirectionType.Up); - break; - case "buttonDown": - result = _drawningAntiAircraftGun.MoveTransport(DirectionType.Down); - break; - case "buttonRight": - result = _drawningAntiAircraftGun.MoveTransport(DirectionType.Right); - break; - case "buttonLeft": - result = _drawningAntiAircraftGun.MoveTransport(DirectionType.Left); - break; - } - if (result) - { - Draw(); - } + _strategy.SetData(new MoveableAircraftGun(_drawningAircraftGun), pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.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/AntiAircraftGun/MovementStrategy/AbstractStrategy.cs b/AntiAircraftGun/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..1770a26 --- /dev/null +++ b/AntiAircraftGun/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,121 @@ +namespace AntiAircraftGun.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/AntiAircraftGun/MovementStrategy/IMoveableObject.cs b/AntiAircraftGun/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..aa69a12 --- /dev/null +++ b/AntiAircraftGun/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,19 @@ +namespace AntiAircraftGun.MovementStrategy; + +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/AntiAircraftGun/MovementStrategy/MoveToBorder.cs b/AntiAircraftGun/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..f5b66e3 --- /dev/null +++ b/AntiAircraftGun/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,50 @@ +namespace AntiAircraftGun.MovementStrategy; + +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth + && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth && + objParams.ObjectMiddleVertical - GetStep() <= FieldHeight + && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight; + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + int diffX = objParams.ObjectMiddleHorizontal - FieldWidth; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + int diffY = objParams.ObjectMiddleVertical - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } +} diff --git a/AntiAircraftGun/MovementStrategy/MoveToCenter.cs b/AntiAircraftGun/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..8700703 --- /dev/null +++ b/AntiAircraftGun/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.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/AntiAircraftGun/MovementStrategy/MoveableAircraftGun.cs b/AntiAircraftGun/MovementStrategy/MoveableAircraftGun.cs new file mode 100644 index 0000000..94b93bb --- /dev/null +++ b/AntiAircraftGun/MovementStrategy/MoveableAircraftGun.cs @@ -0,0 +1,58 @@ +using AntiAircraftGun.Drawnings; + +namespace AntiAircraftGun.MovementStrategy; + +public class MoveableAircraftGun: IMoveableObject +{ + /// + /// Поле-объект класса DrawningAircraftGun или его наследника + /// + private readonly DrawningAircraftGun? _drawningAircraftGun = null; + /// + /// Конструктор + /// + /// Объект класса DrawningTrans + public MoveableAircraftGun(DrawningAircraftGun trans) + { + _drawningAircraftGun = trans; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_drawningAircraftGun == null || _drawningAircraftGun.EntityAircraftGun == null || + !_drawningAircraftGun.GetPosX.HasValue || !_drawningAircraftGun.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_drawningAircraftGun.GetPosX.Value, + _drawningAircraftGun.GetPosY.Value, _drawningAircraftGun.GetWidth, _drawningAircraftGun.GetHeight); + } + } + public int GetStep => (int)(_drawningAircraftGun?.EntityAircraftGun?.Step ?? 0); + public bool TryMoveObject(MovementDirection direction) + { + if (_drawningAircraftGun == null || _drawningAircraftGun.EntityAircraftGun == null) + { + return false; + } + return _drawningAircraftGun.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/AntiAircraftGun/MovementStrategy/MovementDirection.cs b/AntiAircraftGun/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..38e1227 --- /dev/null +++ b/AntiAircraftGun/MovementStrategy/MovementDirection.cs @@ -0,0 +1,21 @@ +namespace AntiAircraftGun.MovementStrategy; + +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 +} diff --git a/AntiAircraftGun/MovementStrategy/ObjectParameters.cs b/AntiAircraftGun/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..3ce8dfc --- /dev/null +++ b/AntiAircraftGun/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,59 @@ +namespace AntiAircraftGun.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/AntiAircraftGun/MovementStrategy/StrategyStatus.cs b/AntiAircraftGun/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..5b78ebe --- /dev/null +++ b/AntiAircraftGun/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,17 @@ +namespace AntiAircraftGun.MovementStrategy; + +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + /// + /// Выполняется + /// + InProgress, + /// + /// Завершено + /// + Finish +}