diff --git a/ProjectTank/ProjectTank/DirectionType.cs b/ProjectTank/ProjectTank/DirectionType.cs deleted file mode 100644 index 31f8f61..0000000 --- a/ProjectTank/ProjectTank/DirectionType.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace ProjectTank; -/// -/// Направление перемещения -/// -public enum DirectionType -{ - /// - /// Вверх - /// - Up = 1, - /// - /// Вниз - /// - Down = 2, - /// - /// Влево - /// - Left = 3, - /// - /// Вправо - /// - Right = 4 -} diff --git a/ProjectTank/ProjectTank/Drawnings/DirectionType.cs b/ProjectTank/ProjectTank/Drawnings/DirectionType.cs new file mode 100644 index 0000000..617ff20 --- /dev/null +++ b/ProjectTank/ProjectTank/Drawnings/DirectionType.cs @@ -0,0 +1,27 @@ +namespace ProjectTank.Drawnings; +/// +/// +/// +public enum DirectionType +{ + /// + /// + /// + Unknow = -1, + /// + /// + /// + Up = 1, + /// + /// + /// + Down = 2, + /// + /// + /// + Left = 3, + /// + /// + /// + Right = 4 +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/Drawnings/DrawningMilitaryTank.cs b/ProjectTank/ProjectTank/Drawnings/DrawningMilitaryTank.cs new file mode 100644 index 0000000..d221496 --- /dev/null +++ b/ProjectTank/ProjectTank/Drawnings/DrawningMilitaryTank.cs @@ -0,0 +1,66 @@ +using System.Drawing.Drawing2D; +using ProjectTank.Entities; + +namespace ProjectTank.Drawnings +{ + public class DrawningMilitaryTank : DrawningTank + { + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия вертолетной площадки + /// Признак наличия шлюпок + /// Признак наличия пушки + + public DrawningMilitaryTank(int speed, double weight, Color bodyColor, Color additionalColor, bool helicopterArea, bool gun, bool luke) + : base(150, 50) + { + EntityTank = new EntityMilitaryTank(speed, weight, bodyColor, additionalColor, helicopterArea, gun, luke); + } + + public override void DrawTransport(Graphics g) + { + if (EntityTank == null || EntityTank is not EntityMilitaryTank entityMilitaryTank || !_startPosX.HasValue || + !_startPosY.HasValue) + { + return; + } + + Pen pen2 = new(Color.Black, 2); + Brush Brush = new SolidBrush(Color.Black); + Brush Brush2 = new SolidBrush(entityMilitaryTank.AdditionalColor); + Brush additionalBrush = new SolidBrush(entityMilitaryTank.AdditionalColor); + + base.DrawTransport(g); + + g.FillRectangle(Brush2, _startPosX.Value + 7, _startPosY.Value + 15, 132, 10); + g.DrawRectangle(pen2, _startPosX.Value + 7, _startPosY.Value + 15, 132, 10); + + if (entityMilitaryTank.Muzzle) + { + g.FillRectangle(additionalBrush, _startPosX.Value + 10, _startPosY.Value + 5, 35, 3); + g.DrawRectangle(pen2, _startPosX.Value + 10, _startPosY.Value + 5, 35, 3); + } + + if (entityMilitaryTank.Gun) + { + g.DrawLine(pen2, _startPosX.Value + 100, _startPosY.Value + 15, _startPosX.Value + 110, _startPosY.Value + 10); + g.DrawLine(pen2, _startPosX.Value + 110, _startPosY.Value + 15, _startPosX.Value + 110, _startPosY.Value + 10); + g.DrawLine(pen2, _startPosX.Value + 120, _startPosY.Value + 15, _startPosX.Value + 110, _startPosY.Value + 10); + g.FillRectangle(Brush, _startPosX.Value + 100, _startPosY.Value + 3, 20, 7); + g.FillRectangle(Brush, _startPosX.Value + 120, _startPosY.Value + 5, 20, 2); + } + + if (entityMilitaryTank.Luke) + { + g.DrawRectangle(pen2, _startPosX.Value + 60, _startPosY.Value - 2, 25, 2); + } + + } + } +} diff --git a/ProjectTank/ProjectTank/DrawningTank.cs b/ProjectTank/ProjectTank/Drawnings/DrawningTank.cs similarity index 70% rename from ProjectTank/ProjectTank/DrawningTank.cs rename to ProjectTank/ProjectTank/Drawnings/DrawningTank.cs index 9cecaf5..7bec0c8 100644 --- a/ProjectTank/ProjectTank/DrawningTank.cs +++ b/ProjectTank/ProjectTank/Drawnings/DrawningTank.cs @@ -1,8 +1,6 @@ -using ProjectTank; -using System.Drawing.Drawing2D; -using System.Security.Cryptography.Xml; +using ProjectTank.Entities; -namespace ProjectTank; +namespace ProjectTank.Drawnings; /// /// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// @@ -11,7 +9,7 @@ public class DrawningTank /// /// Класс-сущность /// - public EntityTank? EntityTank { get; private set; } + public EntityTank? EntityTank { get; protected set; } /// /// Ширина окна /// @@ -23,43 +21,71 @@ public class DrawningTank /// /// Левая координата прорисовки автомобиля /// - private int? _startPosX; + protected int? _startPosX; /// /// Верхняя кооридната прорисовки автомобиля /// - private int? _startPosY; + protected int? _startPosY; /// /// Ширина прорисовки танка /// private readonly int _drawningTankWidth = 150; /// - /// Высота прорисовки танка + /// Высота прорисовки танка /// private readonly int _drawningTankHeight = 50; private readonly int _drawningEnginesWidth = 3; - /// - /// Инициализация свойств - /// - /// Скорость - /// Вес - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия вертолетной площадки - /// Признак наличия шлюпок - /// Признак наличия пушки - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool motor, bool boat, bool glass) + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _drawningTankWidth; + /// + /// Высота объекта + /// + public int GetHeight => _drawningTankHeight; + + /// + /// Пустой онструктор + /// + private DrawningTank() { - EntityTank = new EntityTank(); - EntityTank.Init(speed, weight, bodyColor, additionalColor, - motor, boat, glass); _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + public DrawningTank(int speed, double weight, Color bodyColor) : this() + { + EntityTank = new EntityTank(speed, weight, bodyColor); + } + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки автомобиля + /// Высота прорисовки автомобиля + protected DrawningTank(int drawningCarWidth, int drawningCarHeight) : this() + { + _drawningTankWidth = drawningCarWidth; + _pictureHeight = drawningCarHeight; + } + /// /// Установка границ поля /// @@ -161,32 +187,29 @@ public class DrawningTank /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { if (EntityTank == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } - Pen pen = new(EntityTank.BodyColor, 2); Pen pen2 = new(Color.Black, 2); Pen pen3 = new(Color.Black, 3); - Brush Brush = new SolidBrush(Color.Black); - Brush Brush2 = new SolidBrush(EntityTank.AdditionalColor); - Brush additionalBrush = new SolidBrush(EntityTank.AdditionalColor); + Brush Brush = new SolidBrush(EntityTank.BodyColor); //границы танка - g.DrawRectangle(pen, _startPosX.Value + 45, _startPosY.Value, 50, 15); - g.FillRectangle(additionalBrush, _startPosX.Value + 45, _startPosY.Value, 50, 15); + g.FillRectangle(Brush, _startPosX.Value + 45, _startPosY.Value, 50, 15); + g.DrawRectangle(pen2, _startPosX.Value + 45, _startPosY.Value, 50, 15); - g.DrawRectangle(pen, _startPosX.Value + 7, _startPosY.Value + 15, 132, 10); - g.FillRectangle(additionalBrush, _startPosX.Value + 7, _startPosY.Value + 15, 132, 10); + g.FillRectangle(Brush, _startPosX.Value + 7, _startPosY.Value + 15, 132, 10); + g.DrawRectangle(pen2, _startPosX.Value + 7, _startPosY.Value + 15, 132, 10); g.DrawArc(pen2, _startPosX.Value, _startPosY.Value + 22, 25, 25, 70, 200); g.DrawArc(pen2, _startPosX.Value + 122, _startPosY.Value + 22, 25, 25, 260, 200); g.DrawLine(pen2, _startPosX.Value + 10, _startPosY.Value + 23, _startPosX.Value + 135, _startPosY.Value + 23); g.DrawLine(pen2, _startPosX.Value + 10, _startPosY.Value + 47, _startPosX.Value + 135, _startPosY.Value + 47); - g.DrawEllipse(pen3, _startPosX.Value + 5, _startPosY.Value + 25 , 18, 18); + g.DrawEllipse(pen3, _startPosX.Value + 5, _startPosY.Value + 25, 18, 18); g.DrawEllipse(pen3, _startPosX.Value + 125, _startPosY.Value + 25, 18, 18); g.DrawEllipse(pen3, _startPosX.Value + 103, _startPosY.Value + 31, 12, 12); g.DrawEllipse(pen3, _startPosX.Value + 34, _startPosY.Value + 31, 12, 12); @@ -196,26 +219,5 @@ public class DrawningTank g.DrawArc(pen2, _startPosX.Value + 70, _startPosY.Value + 18, 10, 10, 0, 170); g.DrawArc(pen2, _startPosX.Value + 93, _startPosY.Value + 18, 10, 10, 0, 170); - //внутренности танка - - if (EntityTank.Muzzle) - { - g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 5, 35, 3); - g.FillRectangle(additionalBrush, _startPosX.Value + 10, _startPosY.Value + 5, 35, 3); - } - - if (EntityTank.Gun) - { - g.DrawLine(pen2, _startPosX.Value + 100, _startPosY.Value + 15, _startPosX.Value + 110, _startPosY.Value + 10); - g.DrawLine(pen2, _startPosX.Value + 110, _startPosY.Value + 15, _startPosX.Value + 110, _startPosY.Value + 10); - g.DrawLine(pen2, _startPosX.Value + 120, _startPosY.Value + 15, _startPosX.Value + 110, _startPosY.Value + 10); - g.FillRectangle(Brush, _startPosX.Value + 100, _startPosY.Value + 3, 20, 7); - g.FillRectangle(Brush, _startPosX.Value + 120, _startPosY.Value + 5, 20, 2); - } - - if (EntityTank.Luke) - { - g.DrawRectangle(pen, _startPosX.Value + 60, _startPosY.Value - 2, 25, 2); - } } -} +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/Entities/EntityMilitaryTank.cs b/ProjectTank/ProjectTank/Entities/EntityMilitaryTank.cs new file mode 100644 index 0000000..d75cbac --- /dev/null +++ b/ProjectTank/ProjectTank/Entities/EntityMilitaryTank.cs @@ -0,0 +1,30 @@ +namespace ProjectTank.Entities +{ + internal class EntityMilitaryTank : EntityTank + { + /// + /// Признак (опция) наличие пушка + /// + public bool Muzzle { get; private set; } + /// + /// Признак (опция) наличие артелирийской пушки + /// + public bool Gun { get; private set; } + /// + /// Признак (опция) наличие люка + /// + public bool Luke { get; private set; } + /// + /// Дополнительный цвет (для опциональных элементов) + /// + public Color AdditionalColor { get; private set; } + + public EntityMilitaryTank(int speed, double weight, Color bodyColor, Color additionalColor, bool мuzzle, bool gun, bool luke) : base(speed, weight, bodyColor) + { + AdditionalColor = additionalColor; + Muzzle = мuzzle; + Gun = gun; + Luke = luke; + } + } +} diff --git a/ProjectTank/ProjectTank/Entities/EntityTank.cs b/ProjectTank/ProjectTank/Entities/EntityTank.cs new file mode 100644 index 0000000..253c8a4 --- /dev/null +++ b/ProjectTank/ProjectTank/Entities/EntityTank.cs @@ -0,0 +1,38 @@ +namespace ProjectTank.Entities; + +/// +/// Класс-сущность "танк" +/// +public class EntityTank +{ + //свойства + /// + /// Скорость + /// + 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 EntityTank(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } +} diff --git a/ProjectTank/ProjectTank/EntityTank.cs b/ProjectTank/ProjectTank/EntityTank.cs deleted file mode 100644 index 79fa6ff..0000000 --- a/ProjectTank/ProjectTank/EntityTank.cs +++ /dev/null @@ -1,62 +0,0 @@ -namespace ProjectTank; -/// -/// Класс-сущность "автобус" -/// -public class EntityTank -{ - //свойства - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } - /// - /// Дополнительный цвет (для опциональных элементов) - /// - public Color AdditionalColor { get; private set; } - /// - /// Признак (опция) наличие второго этажа - /// - public bool Muzzle { get; private set; } - /// - /// Признак (опция) наличие лестницы - /// - public bool Gun { get; private set; } - /// - /// Признак (опция) наличие фар - /// - public bool Luke { get; private set; } - //поле класса - /// - /// Шаг перемещения автомобиля - /// - public double Step => Speed * 100 / Weight; - /// - /// Инициализация полей объекта-класса танк - /// - /// скорость - /// вес - /// основной цвет - /// дополнительный цвет - /// второй этаж - /// лестница - /// наличие фар - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool motor, bool oars, bool glass) - { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; - AdditionalColor = additionalColor; - Muzzle = motor; - Gun = oars; - Luke = glass; - } -} diff --git a/ProjectTank/ProjectTank/FormTank.Designer.cs b/ProjectTank/ProjectTank/FormTank.Designer.cs index 3321e90..eca5964 100644 --- a/ProjectTank/ProjectTank/FormTank.Designer.cs +++ b/ProjectTank/ProjectTank/FormTank.Designer.cs @@ -1,5 +1,4 @@ - -namespace ProjectTank +namespace ProjectTank { partial class FormTank { @@ -30,25 +29,28 @@ namespace ProjectTank private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormTank)); - pictureBox1 = new PictureBox(); + pictureBoxTank = new PictureBox(); button1 = new Button(); buttonUp = new Button(); buttonDown = new Button(); buttonRight = new Button(); buttonLeft = new Button(); - ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); + comboBoxStrategy = new ComboBox(); + buttonCretaeTank = new Button(); + buttonStrategyStep = new Button(); + ((System.ComponentModel.ISupportInitialize)pictureBoxTank).BeginInit(); SuspendLayout(); // - // pictureBox1 + // pictureBoxTank // - pictureBox1.Dock = DockStyle.Fill; - pictureBox1.Location = new Point(0, 0); - pictureBox1.Margin = new Padding(3, 2, 3, 2); - pictureBox1.Name = "pictureBox1"; - pictureBox1.Size = new Size(700, 338); - pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize; - pictureBox1.TabIndex = 0; - pictureBox1.TabStop = false; + pictureBoxTank.Dock = DockStyle.Fill; + pictureBoxTank.Location = new Point(0, 0); + pictureBoxTank.Margin = new Padding(3, 2, 3, 2); + pictureBoxTank.Name = "pictureBoxTank"; + pictureBoxTank.Size = new Size(700, 338); + pictureBoxTank.SizeMode = PictureBoxSizeMode.AutoSize; + pictureBoxTank.TabIndex = 0; + pictureBoxTank.TabStop = false; // // button1 // @@ -56,9 +58,9 @@ namespace ProjectTank button1.Location = new Point(10, 307); button1.Margin = new Padding(3, 2, 3, 2); button1.Name = "button1"; - button1.Size = new Size(82, 22); + button1.Size = new Size(186, 22); button1.TabIndex = 1; - button1.Text = "создать"; + button1.Text = "создать военный танк"; button1.UseVisualStyleBackColor = true; button1.Click += ButtonCreateTank_Click; // @@ -114,34 +116,74 @@ namespace ProjectTank buttonLeft.UseVisualStyleBackColor = true; buttonLeft.Click += ButtonMove_Click; // + // comboBoxStrategy + // + comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right; + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "к центру", "к краю" }); + comboBoxStrategy.Location = new Point(557, 9); + comboBoxStrategy.Margin = new Padding(3, 2, 3, 2); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(133, 23); + comboBoxStrategy.TabIndex = 6; + // + // buttonCretaeTank + // + buttonCretaeTank.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCretaeTank.Location = new Point(210, 308); + buttonCretaeTank.Margin = new Padding(3, 2, 3, 2); + buttonCretaeTank.Name = "buttonCretaeTank"; + buttonCretaeTank.Size = new Size(186, 22); + buttonCretaeTank.TabIndex = 7; + buttonCretaeTank.Text = "создать танк"; + buttonCretaeTank.UseVisualStyleBackColor = true; + buttonCretaeTank.Click += buttonCretaeTank_Click; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(607, 34); + buttonStrategyStep.Margin = new Padding(3, 2, 3, 2); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(82, 22); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormTank // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(700, 338); + Controls.Add(buttonStrategyStep); + Controls.Add(buttonCretaeTank); + Controls.Add(comboBoxStrategy); Controls.Add(buttonLeft); Controls.Add(buttonRight); Controls.Add(buttonDown); Controls.Add(buttonUp); Controls.Add(button1); - Controls.Add(pictureBox1); + Controls.Add(pictureBoxTank); Margin = new Padding(3, 2, 3, 2); Name = "FormTank"; Text = "FormTank"; - //Load += this.FormTank_Load_1; Click += ButtonMove_Click; - ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); + ((System.ComponentModel.ISupportInitialize)pictureBoxTank).EndInit(); ResumeLayout(false); PerformLayout(); } #endregion - private PictureBox pictureBox1; + private PictureBox pictureBoxTank; private Button button1; private Button buttonUp; private Button buttonDown; private Button buttonRight; private Button buttonLeft; + private ComboBox comboBoxStrategy; + private Button buttonCretaeTank; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectTank/ProjectTank/FormTank.cs b/ProjectTank/ProjectTank/FormTank.cs index fc6b2cd..f960ab9 100644 --- a/ProjectTank/ProjectTank/FormTank.cs +++ b/ProjectTank/ProjectTank/FormTank.cs @@ -1,4 +1,7 @@ -namespace ProjectTank +using ProjectTank.Drawnings; +using ProjectTank.MovementStrategy; + +namespace ProjectTank { public partial class FormTank : Form { @@ -6,10 +9,16 @@ /// Поле-объект для прорисовки объекта /// private DrawningTank? _drawningTank; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + public FormTank() { InitializeComponent(); - + _strategy = null; } /// @@ -21,35 +30,64 @@ { return; } - Bitmap bmp = new(pictureBox1.Width, - pictureBox1.Height); + Bitmap bmp = new(pictureBoxTank.Width, + pictureBoxTank.Height); Graphics gr = Graphics.FromImage(bmp); _drawningTank.DrawTransport(gr); - pictureBox1.Image = bmp; + pictureBoxTank.Image = bmp; } + /// - /// Обработка нажатия кнопки "Создать" + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawningTank): + _drawningTank = new DrawningTank(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(DrawningMilitaryTank): + _drawningTank = new DrawningMilitaryTank(random.Next(100, + 300), random.Next(1000, 3000), + Color.FromArgb(random.Next(0, 256), + random.Next(0, 256), random.Next(0, 256)), + Color.FromArgb(random.Next(0, 256), + random.Next(0, 256), random.Next(0, 256)), + Convert.ToBoolean(random.Next(0, 2)), + Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + break; + default: + return; + } + _drawningTank.SetPictureSize(pictureBoxTank.Width, + pictureBoxTank.Height); + _drawningTank.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } + + /// + /// Обработка нажатия кнопки "Создать военный танк" /// /// /// - private void ButtonCreateTank_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningTank = new DrawningTank(); - _drawningTank.Init(random.Next(100, 300), random.Next(1000, 3000), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), - random.Next(0, 256)), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), - random.Next(0, 256)), - Convert.ToBoolean(random.Next(0, 2)), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); - _drawningTank.SetPictureSize(pictureBox1.Width, - pictureBox1.Height); + private void ButtonCreateTank_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningMilitaryTank)); + + /// + /// Обработка нажатия кнопки "Создать танк" + /// + /// + /// + private void buttonCretaeTank_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank)); + - //начальное положение круисера - _drawningTank.SetPosition(random.Next(10, 100), random.Next(10, 100)); - Draw(); - } /// /// Перемещение объекта по форме (нажатие кнопок навигации) /// @@ -87,5 +125,50 @@ Draw(); } } + + /// + /// обработка нажатия кнопки шаг + /// + /// + /// + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningTank == null) + { + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableTank(_drawningTank), pictureBoxTank.Width, pictureBoxTank.Height); + } + + if (_strategy == null) + { + return; + } + + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } + } } diff --git a/ProjectTank/ProjectTank/FormTank.resx b/ProjectTank/ProjectTank/FormTank.resx index ead51ca..8a26dc4 100644 --- a/ProjectTank/ProjectTank/FormTank.resx +++ b/ProjectTank/ProjectTank/FormTank.resx @@ -121,7 +121,7 @@ iVBORw0KGgoAAAANSUhEUgAABGsAAAZACAYAAADO3c9BAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - vQAADr0BR/uQrQAAVu1JREFUeF7s3XHE5XXe//HcstZKkiRJMpIkSZIkSZJkJUmSlSRZK1lJxkokK0mS + vAAADrwBlbxySQAAVu1JREFUeF7s3XHE5XXe//HcstZKkiRJMpIkSZIkSZJkJUmSlSRZK1lJxkokK0mS JGtkJUmSJEkykiRJMpIkyRgjY4wxxhhjjN/v9dnd7rutz3xmrus61/uc8z2PJw+/2++/na7rnO/3dZ3z +Z4iSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk SZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk @@ -498,7 +498,7 @@ iVBORw0KGgoAAAANSUhEUgAABGsAAAZACAYAAADO3c9BAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - vQAADr0BR/uQrQAAVmJJREFUeF7s3XGk5nX+//98ZK2VJEkykpEkSZKsJEmyspIkyUqSrJWsJGMlkpUk + vAAADrwBlbxySQAAVmJJREFUeF7s3XGk5nX+//98ZK2VJEkykpEkSZKsJEmyspIkyUqSrJWsJGMlkpUk SZKVrCRZSVYyVpIkSZKRJEnGGBljjDHGGGP8fo/37mc/36199WzOnHOe531d1+3Ozf69zTnX9X4/znW9 3qdJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJ kiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJ @@ -873,7 +873,7 @@ iVBORw0KGgoAAAANSUhEUgAABkAAAARrCAYAAADb+Gp7AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - vQAADr0BR/uQrQAASClJREFUeF7s3Q+k3vX///F85SNJJjMzk0ySyXwkk8nMJEkyyWQySSaZZGYmGUmS + vAAADrwBlbxySQAASClJREFUeF7s3Q+k3vX///F85SNJJjMzk0ySyXwkk8nMJEkyyWQySSaZZGYmGUmS ZJJJZpLMJJlkJjOZj5mZmZmZyczMzBwzxxzHMcfv93hXq7ad/+d9Xdf7/Xrf7tx8vt+vjy/V2RXn4Xq+ 7pMkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk SZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk @@ -1187,7 +1187,7 @@ iVBORw0KGgoAAAANSUhEUgAABkAAAARrCAYAAADb+Gp7AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - vQAADr0BR/uQrQAAUVNJREFUeF7s3X/E34X+//F85DiSTDKTSSbJJEcySZIkSZJkkiTJ5EiSZJJIkiRJ + vAAADrwBlbxySQAAUVNJREFUeF7s3X/E34X+//F85DiSTDKTSSbJJEcySZIkSZJkkiTJ5EiSZJJIkiRJ JpkkSZJMMpNM5pjMzMzMTGZmZmZmZuZymcv3+3idTufU9tyuX+8frx+3OzfO+bPrer9fF8+Hvd9XSZIk SZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk SZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk diff --git a/ProjectTank/ProjectTank/MovementStrategy/AbstractStrategy.cs b/ProjectTank/ProjectTank/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..c2dea3d --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,123 @@ +namespace ProjectTank.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/ProjectTank/ProjectTank/MovementStrategy/IMoveableObject.cs b/ProjectTank/ProjectTank/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..ae59d1f --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,24 @@ +namespace ProjectTank.MovementStrategy +{ + /// + /// Интерфейс для работы с перемещаемым объектом + /// + public interface IMoveableObject + { + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); + } + +} diff --git a/ProjectTank/ProjectTank/MovementStrategy/MoveToBorder.cs b/ProjectTank/ProjectTank/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..4803477 --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,53 @@ +namespace ProjectTank.MovementStrategy +{ + /// + /// Стратегия перемещения объекта к краю экрана + /// + internal class MoveToBorder : AbstractStrategy + { + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.RightBorder - GetStep() <= FieldWidth + && objParams.RightBorder + GetStep() >= FieldWidth && + objParams.DownBorder - GetStep() <= FieldHeight + && objParams.DownBorder + GetStep() >= FieldHeight; + } + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + int diffX = objParams.RightBorder - FieldWidth; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + int diffY = objParams.DownBorder - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } + } +} diff --git a/ProjectTank/ProjectTank/MovementStrategy/MoveToCenter.cs b/ProjectTank/ProjectTank/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..9f61f22 --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,53 @@ +namespace ProjectTank.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/ProjectTank/ProjectTank/MovementStrategy/MoveableTank.cs b/ProjectTank/ProjectTank/MovementStrategy/MoveableTank.cs new file mode 100644 index 0000000..a87b19d --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/MoveableTank.cs @@ -0,0 +1,62 @@ +using ProjectTank.Drawnings; + +namespace ProjectTank.MovementStrategy +{ + /// + /// класс реалтзация для IMoveableObject с использованием DrawningTank + /// + public class MoveableTank : IMoveableObject + { + /// + /// Поле-объект класса DrawningTank или его наследника + /// + private readonly DrawningTank? _cruiser = null; + /// + /// Конструктор + /// + /// Объект класса DrawningTank + public MoveableTank(DrawningTank cruiser) + { + _cruiser = cruiser; + } + public ObjectParameters? GetObjectPosition + { + get + { + if (_cruiser == null || _cruiser.EntityTank == null || + !_cruiser.GetPosX.HasValue || !_cruiser.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_cruiser.GetPosX.Value, + _cruiser.GetPosY.Value, _cruiser.GetWidth, _cruiser.GetHeight); + } + } + public int GetStep => (int)(_cruiser?.EntityTank?.Step ?? 0); + public bool TryMoveObject(MovementDirection direction) + { + if (_cruiser == null || _cruiser.EntityTank == null) + { + return false; + } + return _cruiser.MoveTransport(GetDirectionType(direction)); + } + /// + /// Конвертация из MovementDirection в DirectionType + /// + /// MovementDirection + /// DirectionType + private static DirectionType GetDirectionType(MovementDirection direction) + { + return direction switch + { + MovementDirection.Left => DirectionType.Left, + MovementDirection.Right => DirectionType.Right, + MovementDirection.Up => DirectionType.Up, + MovementDirection.Down => DirectionType.Down, + _ => DirectionType.Unknow, + }; + } + } +} + diff --git a/ProjectTank/ProjectTank/MovementStrategy/MovementDirection.cs b/ProjectTank/ProjectTank/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..478ab89 --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/MovementDirection.cs @@ -0,0 +1,26 @@ +namespace ProjectTank.MovementStrategy +{ + /// + /// Направление перемещения + /// + public enum MovementDirection + { + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 + } + +} diff --git a/ProjectTank/ProjectTank/MovementStrategy/ObjectParameters.cs b/ProjectTank/ProjectTank/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..c83ed58 --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,64 @@ +namespace ProjectTank.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/ProjectTank/ProjectTank/MovementStrategy/StrategyStatus.cs b/ProjectTank/ProjectTank/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..756a8cc --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,22 @@ +namespace ProjectTank.MovementStrategy +{ + /// + /// Статус выполнения операции перемещения + /// + public enum StrategyStatus + { + /// + /// Все готово к началу + /// + NotInit, + /// + /// Выполняется + /// + InProgress, + /// + /// Завершено + /// + Finish + } + +}